<?php

namespace app\controller;

use app\BaseController;
use app\branch;
use app\message;
use app\model\CluePerson;
use app\model\OrderDeal;
use app\model\OrderDealChargeback;
use app\model\OrderEnterpriseCertificateBusiness;
use app\model\OrderEnterpriseCertificateRegister;
use app\model\OrderEnterpriseCompany;
use app\model\OrderEnterpriseExchange;
use app\model\OrderLog;
use app\model\OrderOtherCertificateBusiness;
use app\model\OrderPersonCertificateRegister;
use app\model\OrderTransactionLog;
use app\model\OrderTransactionRecord;
use app\model\SystemMenu;
use app\model\SystemMenuDataPower;
use app\model\SystemOperateLog;
use app\model\UnitInfo;
use app\model\User;
use app\model\UserMessage;
use app\model\UserOrganization;
use app\Request;
use app\service\Certificate;
use app\service\Clue;
use app\service\FinanceServer;
use app\service\OrderCertReverseCase;
use app\service\OrderCertTransact;
use app\service\OrderEnterCert;
use app\service\Power;
use app\service\RedisService;
use app\service\System;
use app\stateData;
use app\validate\OrderCertExamine;
use PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price;
use PhpOffice\PhpSpreadsheet\Writer\Exception;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use GatewayClient\Gateway;
use app\service\Order as OrderService;

//require_once 'D:/phpstudy/phpstudy_pro/WWW/ystp/vendor/autoload.php';
class Order extends BaseController
{

    private $CERTIFICATE_PERSON_STATUS = '-1,0,1,2,3,4,5';//要查询人才证书订单状态
    private $CERTIFICATE_ENTERPRISE_STATUS = '1,3';//要查询公司证书订单状态
    private $CERTIFICATE_ENTERPRISE_DZ_STATUS = '2,3';//要查询公司证书倒证订单状态
    private $ORDER_LOG_PERSON_TYPE = 1; //订单日志库
    private $ORDER_LOG_ENTERPRISE_TYPE = 2; //订单日志库
    private $ORDER_LOG_ENTERPRISE_DZ_TYPE = 3; //订单日志库
    private $ORDER_LOG_ENTERPRISE_CER = 4; //订单日志库

    private $ORDER_LOG_ENTERPRISE_BUSINESS = 5; //订单日志库
    private $EXAMINE_PASS = 1; //证书审核通过
    private $EXAMINE_REFUSE = -1; //证书审核通过

    private $ORDER_DEAL_TYPE_ENTERPRISE = 1;//订单成交库
    private $ORDER_DEAL_TYPE_ENTERPRISE_DZ = 2;//订单成交库
    private $ORDER_DEAL_TYPE_CER = 3;//订单成交库

    private $ORDER_DEAL_TYPE_ENTERPRISE_BUSINESS = 4;//订单成交库

    private $ORDER_DEAL_STATUS = 1;//订单成交状态 正常 新出
    private $ORDER_SCZ_STATUS = 12;//订单成交状态 正常 新出
    private $ORDER_DEAL_STATUS_QR = 3;//订单成交状态 正常 新出

    private $Collection = 1;//收款
    private $Payment = 2;//付款
    private $regUnit = 3;//注册单位
    private $employUnit = 2;//聘用单位
    private $pushUnit = 1;//出证单位

    private $regCerRankSuccStatus = 11;//证书匹配完成状态


    /**
     * 订单管理
     */

    /*****************************************************************证书审核*****************************************************************************/
    //获取特价证书审批人
    public function getTjzsUidList(User $user)
    {
        $result = $user->getIsTjzsUidModel();
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    //证书审核列表
    public function getCertificateExamineList(
        OrderPersonCertificateRegister $certificateRegister,
        Request                        $request,
        Power                          $power,
        Clue                           $clue,
        \app\service\OrderCertExamine  $orderCertExamine,
        \app\service\Order             $orderSer,
        Image                          $image,
        RedisService                   $redisService
    ){
        $aliasId = $request->get('aliasId');

        $page = $request->get('page') ?: 0;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $uid = $request->param('user_login_id');
        $param = $request->get();

        //根据条件查询用户范围
        $userData = $power->getUserDataRange($uid);

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $validate = new OrderCertExamine();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }

        //证书审核排序字段
        if (isset($param['sort'])) {
            if ($param['sort'] === 'money') { //用于证书需求匹配 证书按实际收证价格排序
                $sort = 'catual_price DESC';
            } else {
                $sort = 'create_date DESC';
            }
        } else {
            $sort = 'create_date DESC';
        }

        $flag = flagStatus($param);
        $ids = $orderCertExamine->spliceWhere($param);

        $ids = !$ids ? [0] : $ids;
        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);
        $all_ids = $certificateRegister->getWhereInStatusIds($this->CERTIFICATE_PERSON_STATUS, $userData);
        $ids = handlePersonIds($all_ids, $ids, $flag);

        $dataId = $certificateRegister->getWhereInStatusList($sort, $this->CERTIFICATE_PERSON_STATUS, $ids, '', $pageNum, $page);

        $data = $orderSer->isSh($redisService->getOrderZsshData($dataId, $uid), $uid);

        $data = $image->handleList($data, ['contract_file', 'information_file'], true);

        $pages['total'] = $certificateRegister->getWhereInStatusCount($this->CERTIFICATE_PERSON_STATUS, $ids, '');
        $pages['pageNumber'] = $pageNum;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => $data,
            'power' => $fieldListTree
        ], $pages);
    }

    //个人审核列表
    public function getThatPersonExamineList(
        OrderPersonCertificateRegister $certificateRegister,
        Request                        $request,
        Power                          $power,
        \app\service\OrderCertExamine  $orderCertExamine,
        \app\service\Order             $orderSer,
        RedisService                   $redisService
    ){
        $aliasId = $request->get('aliasId');
        $uid = $request->get('user_login_id');
        $page = $request->get('page') ?: 0;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        $param = $request->get();
        $validate = new OrderCertExamine();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }
        $flag = flagStatus($param);
        $ids = $orderCertExamine->spliceWhere($param);

        $ids = !$ids ? [0] : $ids;

        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        $all_ids = $certificateRegister->getWhereThatPersonInStatusIds($this->CERTIFICATE_PERSON_STATUS, $uid);

        $ids = handlePersonIds($all_ids, $ids, $flag);

        $dataId = $certificateRegister->getWhereThatPersonInStatusList($this->CERTIFICATE_PERSON_STATUS, $uid, $ids, '', $pageNum, $page);

        $datas = $orderSer->isSh($redisService->getOrderZsshData($dataId, $uid), $uid);

        $pages['total'] = $certificateRegister->getWhereThatPersonInStatusCount($this->CERTIFICATE_PERSON_STATUS, $uid, $ids, '');
        $pages['pageNumber'] = $pageNum;
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => $datas,
            'power' => $fieldListTree
        ], $pages);
    }

    //证书审核详情
    public function getCertificateExamineDetails(Request $request, OrderPersonCertificateRegister $certificateRegister, OrderLog $log, FinanceServer $financeServer, Image $image)
    {
        $id = $request->get('id');//证书id
        $uid = $request->get('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $result = $certificateRegister->getIdDetails($id);
        if (!$result) {
            return ReJson(message::$ERROR_CODE, message::$ERR_SELECT_NO_DATA);
        }
        //是否有审核权限
        if ($result['responsibility_uid'] && $result['status']['id'] == 0) {//d第一步待审核
            if ($result['responsibility_uid'] == $uid) {
                $result['is_sh'] = 1;
            } else {
                $result['is_sh'] = 0;
            }
        }

        if ($result['certificate_characteristic_reviewed_uid']['id'] && $result['certificate_characteristic_status']['id'] == 2) {
            if ($result['certificate_characteristic_reviewed_uid']['id'] == $uid) {
                $result['is_sh'] = 1;
            } else {
                $result['is_sh'] = 0;
            }
        }

        if (empty($result)) return ReJson(message::$ERROR_CODE, message::$SELECT_CERTIFICATE_ERR);
        if ($result['certificate_id']) {
            $result['certificate_id'] = explode(',', $result['certificate_id']);
            $result['certificate_id'] = array_map('intval', $result['certificate_id']);
        } else {
            $result['certificate_id'] = [];
        }
        //处理多文件上传问题
        $result = $image->handleList($result, ['information_file', 'contract_file']);

        $order_log = $log->getCertificateCodeFindDataModel($result['certificate_code']);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => $result,
            'log' => $order_log
        ]);
    }

    //证书审核通过
    public function setCertificatePass(
        Request                        $request,
        OrderPersonCertificateRegister $certificateRegister,
        OrderLog                       $log,
        UserMessage                    $message,
        Gateway                        $gateway,
        CluePerson                     $person,
        OrderTransactionLog            $orderTransactionLogModel,
        RedisService                   $redisService,
        SystemOperateLog               $systemOperateLogModel
    ){
        $id = $request->post('id');//证书id
        $certificate_code = $request->post('certificate_code');//证书id

        $uid = $request->param('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        //证书详情
        $data = $certificateRegister->getIdDetails($id);

        Db::startTrans();
        try {
            //判断是审核证书还是特价证书
            if ($data['responsibility_uid'] == $uid) {

                if ($data['status']['id'] != 0) {
                    return ReJson(message::$ERROR_CODE, message::$ORDER_CER_STATUS_NO_SH);
                }

                //修改订单为通过状态
                if (!$certificateRegister->editCerRegDataModel([
                    'id' => $id,
                    'status' => $this->EXAMINE_PASS
                ])) {
                    return ReJson(message::$ERROR_CODE, message::$ERR_EXAMINE);
                }
            }

            if ($data['certificate_characteristic_reviewed_uid']['id'] == $uid) {

                if ($data['certificate_characteristic_status']['id'] != 2) {
                    return ReJson(message::$ERROR_CODE, message::$ORDER_CER_STATUS_NO_SH);
                }

                //修改特价证书为通过状态
                if (!$certificateRegister->editCerRegDataModel([
                    'id' => $id,
                    'certificate_characteristic_status' => 1
                ])) {
                    return ReJson(message::$ERROR_CODE, message::$ERR_EXAMINE);
                }
            }

            if (isset($data['certificate_characteristic_reviewed_uid'])) {

                if ($data['certificate_characteristic_reviewed_uid']['id']) {
                    //查询上一条日志是否修改特价证书与基础信息
                    $logData = $log->getOrderLogModel($id, $certificate_code);
                    if (!empty($logData)) {
                        foreach ($logData as $logDatum) {
                            if ($data['certificate_characteristic_reviewed_uid'] == $data['top_certificate_characteristic_reviewed_uid']) {
                                if ($logDatum['message'] == '提交审核-证书审核') {
                                    //添加订单日志
                                    $log->addDataModel([
                                        'submit_id' => $uid,
                                        'message' => message::$ORDER_PERSON_ADD_TEJIA_SUCC,
                                        'type' => $this->ORDER_LOG_PERSON_TYPE,
                                        'order_company_id' => $id,
                                        'certificate_code' => $certificate_code
                                    ]);
                                    break;
                                }
                            } else {
                                if ($logDatum['message'] == '提交审核-特价证书*证书审核') {
                                    //添加订单日志
                                    $log->addDataModel([
                                        'submit_id' => $uid,
                                        'message' => message::$ORDER_PERSON_ADD_TEJIA_YU_SUCC,
                                        'type' => $this->ORDER_LOG_PERSON_TYPE,
                                        'order_company_id' => $id,
                                        'certificate_code' => $certificate_code
                                    ]);
                                    break;
                                }
                            }

                            if ($logDatum['message'] == '提交审核-特价证书') {
                                //添加订单日志
                                $log->addDataModel([
                                    'submit_id' => $uid,
                                    'message' => message::$ORDER_PERSON_ADD_TEJIA_SUCC,
                                    'type' => $this->ORDER_LOG_PERSON_TYPE,
                                    'order_company_id' => $id,
                                    'certificate_code' => $certificate_code
                                ]);
                                break;
                            }

                            if ($logDatum['message'] == '提交审核-证书审核') {
                                //添加订单日志
                                $log->addDataModel([
                                    'submit_id' => $uid,
                                    'message' => message::$ORDER_PERSON_ADD_SUCC,
                                    'type' => $this->ORDER_LOG_PERSON_TYPE,
                                    'order_company_id' => $id,
                                    'certificate_code' => $certificate_code
                                ]);
                                break;
                            }
                        }
                    }

                } else {
                    //添加订单日志
                    $log->addDataModel([
                        'submit_id' => $uid,
                        'message' => message::$ORDER_PERSON_ADD_SUCC,
                        'type' => $this->ORDER_LOG_PERSON_TYPE,
                        'order_company_id' => $id,
                        'certificate_code' => $certificate_code
                    ]);


                }
            } else {

                //添加订单日志
                $log->addDataModel([
                    'submit_id' => $uid,
                    'message' => message::$ORDER_PERSON_ADD_SUCC,
                    'type' => $this->ORDER_LOG_PERSON_TYPE,
                    'order_company_id' => $id,
                    'certificate_code' => $certificate_code
                ]);
            }


            //修改人才状态为代出售
            $person->editStatusModel($data['person_id_card'], 2);

            //添加消息提醒
            $messages = $message->addCertificateExaminePassModel($data['certificate_code'], $data['submit_id'], $uid, $id, date('Y-m-d H:i:s'));

            //发送长连接提醒
            $gateway->sendToUid($data['submit_id'], json_encode($messages));

            $systemOperateLogModel->addOperate($uid, message::$ORDER, '证书审核-通过' . $id);

            //更新缓存内容
            $redisService->updateOrderZsshData($id);
            $redisService->delPersonData($person->getPersonIdCardInfo($data['person_id_card'])['id']);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_EXAMINE);
    }

    //证书审核驳回
    public function CertificateReject(
        Request                        $request,
        OrderPersonCertificateRegister $certificateRegister,
        OrderLog                       $log,
        UserMessage                    $message,
        Gateway                        $gateway,
        RedisService                   $redisService,
        SystemOperateLog               $systemOperateLogModel
    ){
        $id = $request->post('id');//证书id

        $text = $request->post('reason');//驳回原因
        $uid = $fid = $request->post('user_login_id');

        //证书详情
        $data = $certificateRegister->getIdDetails($id);

        if (empty($id) || empty($text)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        // 启动事务
        Db::startTrans();
        try {
            //判断是驳回特价证书还是驳回证书审核
            if ($data['responsibility_uid'] == $uid) {
                if ($data['status']['id'] != 0) return ReJson(message::$ERROR_CODE, message::$ORDER_CER_STATUS_NO_SH);
                $fid = $data['responsibility_uid'];//信息发送人ID
                $jid = $data['submit_id'];//信息接收人
                $certificateRegister->editCerRegDataModel([
                    'id' => $id,
                    'status' => $this->EXAMINE_REFUSE
                ]);
                $log->addDataModel([
                    'submit_id' => $uid,
                    'message' => message::$ORDER_PERSON_ADD_ERR,
                    'content' => $text,
                    'type' => $this->ORDER_LOG_PERSON_TYPE,
                    'order_company_id' => $id,
                    'certificate_code' => $data['certificate_code'],
                    'is_reject' => 1
                ]);

            }

            if ($data['certificate_characteristic_reviewed_uid']['id'] == $uid) {

                if ($data['certificate_characteristic_status']['id'] != 2) return ReJson(message::$ERROR_CODE, message::$ORDER_CER_STATUS_NO_SH);
                $fid = $data['certificate_characteristic_reviewed_uid']['id']; //信息发送人ID
                $jid = $data['submit_id'];//信息接收人
                $certificateRegister->editCerRegDataModel([
                    'id' => $id,
                    'certificate_characteristic_status' => -1
                ]);
                $log->addDataModel([
                    'submit_id' => $uid,
                    'message' => '特价证书审核驳回',
                    'content' => $text,
                    'type' => $this->ORDER_LOG_PERSON_TYPE,
                    'order_company_id' => $id,
                    'certificate_code' => $data['certificate_code'],
                    'is_reject' => 1
                ]);

            }

            //添加消息提醒
            $messages = $message->addCertificateExamineRefuseModel($data['certificate_code'], $jid, $fid, $id, date('Y-m-d H:i:s'));

            $gateway->sendToUid($jid, json_encode($messages));
            //更新缓存内容
            $redisService->updateOrderZsshData($id, $uid);

            $systemOperateLogModel->addOperate($uid, message::$ORDER, '证书审核-驳回' . $id . '原因:' . $text);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$ORDER_PERSON_ADD_ERR);
    }

    //证书审核删除
    public function delCertificate(
        Request                        $request,
        OrderPersonCertificateRegister $certificateRegister,
        OrderLog                       $log,
        CluePerson                     $person,
        RedisService                   $redisService,
        SystemOperateLog               $systemOperateLogModel
    ){
        $id = $ids = $request->post('id');//证书id
        $id = explode(',', $id);
        $uid = $request->post('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //修改人才状态为代收证
        $userData = '';
        foreach ($id as $item) {
            //查询该审核订单身份证对应的人才
            $userData = $certificateRegister->getIdDetails($item);
            //通过身份证修改人才为代收证
            if (isset($userData['person_id_card']) && $userData['person_id_card']) {
                $person->setIdCardStatusSzModel($userData['person_id_card']);
            }
        }

        $certificateRegister->delId($id);
        //删除缓存内容
        $redisService->deleteOrderZsshData($id);
        $systemOperateLogModel->addOperate($uid, message::$ORDER, '证书审核-删除' . $ids);

        return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }

    //证书审核编辑
    public function editCertificate(
        Request                        $request,
        OrderPersonCertificateRegister $certificateRegister,
        OrderLog                       $log,
        Certificate                    $certificateSer,
        UserMessage                    $message,
        Gateway                        $gateway,
        Image                          $image,
        RedisService                   $redisService,
        SystemOperateLog               $systemOperateLogModel
    ){
        $param = $certificateSer->splitCer($request->post());//证书id

        $uid = $request->param('user_login_id');

//        //是否有文件上传
//        $information_file = $request->file('information_file');
//        $contract_file = $request->file('contract_file');

        if (empty($param['id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        try {

//            if($information_file){
//                $param['information_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $information_file);
//            }
//            if ($contract_file){
//                $param['contract_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $contract_file);
//            }

            //去掉url http
            $str = "file/";
            $array = $image->handle($param['contract_file'], 'contract_file', 'contract_file_name');
            $param['contract_file'] = $array['contract_file'];
            $param['contract_file_name'] = $array['contract_file_name'];
            $array = $image->handle($param['information_file'], 'information_file', 'information_file_name');
            $param['information_file'] = $array['information_file'];
            $param['information_file_name'] = $array['information_file_name'];
//            if (!empty($param['contract_file'])){
//                $param['contract_file'] = strstr($param['contract_file'],$str);
//            }
//            if (!empty($param['information_file'])){
//                $param['information_file'] = strstr($param['information_file'],$str);
//            }

            /**
             * 判断是否修改了基础资料
             */
            $originalData = Db::table('order_person_certificate_register')->where('id', $param['id'])->find();
            $isSave = 1;

            //判断源数据与接收数据是否一致
            foreach ($originalData as $k => $originalDatum) {
                if ($k == 'certificate_characteristic_reviewed_uid') {
                    continue;
                }
                if (array_key_exists($k, $param)) {
                    if ($param[$k] != $originalDatum) {
                        $isSave = 2;
                        break;
                    }
                }
            }
            $mess = message::$ORDER_PERSON_EDIT_TEJIA_YU_SUCC;
            //判断是否设置为特价证书
            if ($param['certificate_characteristic'] == 1) {


                if (empty($param['certificate_characteristic_reviewed_uid'])) {
                    return ReJson(message::$ERROR_CODE, '未设置特价证书审核人');
                }
                $mesUid = $param['certificate_characteristic_reviewed_uid'];

                //查询当前信息是否有特价证书审核人
                if ($originalData['certificate_characteristic_reviewed_uid']) {

                    if ($originalData['certificate_characteristic_reviewed_uid'] == $param['certificate_characteristic_reviewed_uid']) {
                        //判断是否为驳回状态 驳回状态提交给特价证书审核人进行修改
                        if ($originalData['certificate_characteristic_status'] > 0) {
                            $mess = message::$ORDER_PERSON_EDIT_SUCC;
                            $mesUid = $originalData['responsibility_uid'];

                            //如果证书已售出 不改变售出状态
                            if ($originalData['status'] != 3) {
                                $param['status'] = 0;
                            }
                        } else {
                            $param['certificate_characteristic_status'] = 2; //证书审核编辑一次就修改为待审核
                        }
                    } else {
                        $param['certificate_characteristic_status'] = 2; //证书审核编辑一次就修改为待审核
                    }

                    $param['top_certificate_characteristic_reviewed_uid'] = $originalData['certificate_characteristic_reviewed_uid'];//如果有 记录当前审核人为上一次审核人 然后更新
                } else {
                    $param['certificate_characteristic_status'] = 2; //证书审核编辑一次就修改为待审核
                }

                //修改资料
                $certificateRegister->editId($param);

                /**
                 * 判断是否也修改了基础资料
                 */
                if ($isSave == 1) {
                    $log->addDataModel([
                        'submit_id' => $request->param('user_login_id'),
                        'message' => message::$ORDER_PERSON_EDIT_TEJIA_SUCC,
                        'type' => $this->ORDER_LOG_PERSON_TYPE,
                        'certificate_code' => $param['certificate_code'],
                        'order_company_id' => $param['id']
                    ]);
                } else if ($isSave == 2) {
                    $log->addDataModel([
                        'submit_id' => $request->param('user_login_id'),
                        'message' => $mess,
                        'type' => $this->ORDER_LOG_PERSON_TYPE,
                        'certificate_code' => $param['certificate_code'],
                        'order_company_id' => $param['id']
                    ]);
                }

                //添加附加业务消息提醒
//                $messages = $message->addCertificateExamineModel($param['certificate_code'],$originalData['responsibility_uid'],$uid,$param['id']);
//                //发送用户提醒
//                $gateway->sendToUid($originalData['responsibility_uid'],json_encode($messages));
                //删除缓存
                $redisService->deleteOrderZsshData($param['id'], $uid);
                //添加附加业务消息提醒
                $messages = $message->addCertificateExamineModel($param['certificate_code'], $mesUid, $uid, $param['id']);
                //发送用户提醒
                $gateway->sendToUid($mesUid, json_encode($messages));

            } else {
                if ($originalData['status'] != 3) {
                    $param['status'] = 0; //证书审核编辑一次就修改为待审核
                    //证书提交审核日志
                    $log->addDataModel([
                        'submit_id' => $request->param('user_login_id'),
                        'message' => message::$ORDER_PERSON_EDIT_SUCC,
                        'type' => $this->ORDER_LOG_PERSON_TYPE,
                        'certificate_code' => $param['certificate_code'],
                        'order_company_id' => $param['id']
                    ]);
                }

                $param['certificate_characteristic_status'] = 0;
                $param['certificate_characteristic_reviewed_uid'] = 0;
                $certificateRegister->editId($param);

                //添加附加业务消息提醒
                $messages = $message->addCertificateExamineModel($param['certificate_code'], $originalData['responsibility_uid'], $uid, $param['id']);
                //发送用户提醒
                $gateway->sendToUid($originalData['responsibility_uid'], json_encode($messages));
                //更新缓存内容
                $redisService->updateOrderZsshData($param['id'], $uid);

                $systemOperateLogModel->addOperate($uid, message::$ORDER, '证书审核-编辑' . $param['id']);
            }
        } catch (\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    /*****************************************************************证书注册 公司证书*****************************************************************************/

    //证书注册 公司证书需求列表
    public function getEnterPriseCerRegList(
        Request                            $request,
        Power                              $power,
        OrderEnterpriseCertificateRegister $certificateRegister,
        Certificate                        $certificate,
        FinanceServer                      $financeServer
    ){
        $aliasId = $request->get('aliasId');
        $page = $request->get('page') ?: 0;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $param = $request->get();

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $fieldListTree = $power->getUserFieldPower($aliasId, $request->get('user_login_id'));

        $result = $certificateRegister->getRegCerTypeListModel($this->CERTIFICATE_ENTERPRISE_STATUS, $pageNum, $page);

        //条件筛选
        $data = $financeServer->resultSearchHandle($param, $result);

        $pages['total'] = count($data);
        $pages['pageNumber'] = $pageNum;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => page($data, $page, $pageNum, 'asc'),
            'power' => $fieldListTree
        ], $pages);
    }

    //个人查看证书注册列表
    public function getThatPersonEnterPriseCerRegList(
        Request                            $request,
        Power                              $power,
        OrderEnterpriseCertificateRegister $certificateRegister,
        FinanceServer                      $financeServer
    ){
        $aliasId = $request->get('aliasId');
        $page = $request->get('page') ?: 0;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $param = $request->get();

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $fieldListTree = $power->getUserFieldPower($aliasId, $request->get('user_login_id'));

        $result = $certificateRegister->getThatPersonRegCerTypeListModel($this->CERTIFICATE_ENTERPRISE_STATUS, $request->param('user_login_id'), $pageNum, $page);

        //条件筛选
        //改变创建时间筛选为销售时间筛选
//        $param['start_sale_date'] = $param['start_create_date'];
//        $param['end_sale_date'] = $param['end_create_date'];

        $data = $financeServer->resultSearchHandle($param, $result);
        $pages['total'] = count($data);
        $pages['pageNumber'] = stateData::$_page;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => page($data, $page, $pageNum),
            'power' => $fieldListTree
        ], $pages);
    }


    //个人成交证书注册列表
    public function getThatPersonDealCerList(
        Request                $request,
        OrderEnterpriseCompany $company,
        Power                  $power,
        \app\service\Order     $orderSer,
        FinanceServer          $financeServer,
        OrderDeal              $deal,
        OrderDealChargeback    $chargebackModel,
        \app\service\User      $userService,
        RedisService           $redisService
    ){

        $aliasId = $request->get('aliasId');
        $page = $request->get('page') ?: 1;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $uid = $request->param('user_login_id');
        $id = $request->param('id') ?: '';
        $param = $request->get();

        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        //获取用户权限订单id certificate_code sale_date 用来查询缓存
        if ($id) {
            $dataId = $company->getCompanyIdListUidModel($page, $pageNum, $id, $uid);
        } else {
            $dataId = $company->getCompanyListUidModel($page, $pageNum, $uid);
        }
        //查询退单
        $chargebackData = $chargebackModel->getCharDataModel();
        if (!empty($chargebackData)) {
            foreach ($chargebackData as $chargebackDatum) {
                $tData = $company->getCompanyCerIdFindModel($chargebackDatum['order_company_id'], $chargebackDatum['certificate_code']);
                if ($tData) {
                    //判断个人还是管理 增加响应退单内容
                    $idArr = array_column($dataId, 'id');
                    if (in_array($tData['id'], $idArr)) {
//                        if ($chargebackDatum['performance'] > 0){
//                            $tData['performance'] = '-'.$chargebackDatum['performance'];
//                        }else{
//                            $tData['performance'] = $chargebackDatum['performance'];
//                        }

//                        $tData['create_date'] = $chargebackDatum['create_date'];
                        $tData['sale_date'] = $chargebackDatum['create_date'];

//                        $tData['tuidan'] = true;
//                        $tData['reason'] = $chargebackDatum['reason'];
//                        $tData['status'] = [
//                            'id'=>999,
//                            'text'=>'退单完成'
//                        ];
                        $dataId[] = $tData;
                    }
                }
            }
        }

        $result = $redisService->getOrderReKeyDataList($dataId, $uid, 'order_gszs');

        //第二步填写字段
        $zszccj = [
            'employ_unit_title',
            'employ_unit_name',
            'employ_unit_mobile'
        ];
        foreach ($result as &$value) {
            /**
             * 模糊不可见字段
             */
            //判断登录人是否是出证人的领导
            //判断登录人数据可见范围为总公司  或 登录人为出证人的领导
            $witnessLeader = false;
            //判断登录人是否是出证人的领导
            $is_leader = $userService->userIsLeaderUser($uid, $value['sale_uid']['id']);
            //判断登录人数据可见范围是否为总公司
            $powerService = new Power();
            //获取领导人的数据可见范围
            $data_range = $powerService->getUserDataRand($uid);
            if ($data_range == 1 || $is_leader) {
                $witnessLeader = true;
            }

            if (!$witnessLeader) {
                $value['employ_unit_title'] .= '**';
                $value['employ_unit_name'] .= '**';
                $value['employ_unit_mobile'] .= '**';
            }

            //判断第二步是否存在空值
            foreach ($zszccj as $qyzItem) {
                if (array_key_exists($qyzItem, $value)) {
                    if (!$value[$qyzItem]) {
                        $value['is_sup_empty'] = true;
                        continue;
                    }
                    $value['is_sup_empty'] = false;
                }
            }

            //表单定时器
            $dingshiqi = Db::table('user_message')->where([
                'b_id' => $value['certificate_code'],
                'is_executed' => 2,
                'type' => 7,
                'order_company_id' => $value['id']
            ])->find();

            if ($dingshiqi) {
                $value['dingshiqi'] = 1;
            } else {
                $value['dingshiqi'] = 0;
            }
        }

        //处理表单搜索数据
        $data = $orderSer->getOrderIsOp($financeServer->resultSearchHandle($param, ChargeBackDataList($result)));

        $pages['total'] = count($data);
        $pages['pageNumber'] = stateData::$_page;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => page($data, $page, $pageNum, 'desc', 'sale_date'),
            'power' => $fieldListTree
        ], $pages);
    }

    //证书注册详情
    public function getEnterPriseCerDetails(Request $request, OrderEnterpriseCertificateRegister $register, OrderLog $log, \app\service\Order $orderSer)
    {
        $id = $request->get('id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //主证书详情
        $result = $register->getIdDataModel($id);

        //订单流程
        $order_log = $log->getIdFindData($id);

//        //收款信息
//        $result['collection'] = $orderSer->getTransaction($id,$this->Collection);
//
//        //付款信息
//        $result['payment'] = $orderSer->getTransaction($id,$this->Payment);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => $result,
            'log' => $order_log
        ]);
    }

    //个人查询证书注册详情
//    public function getThatPersonCerDetails(
//        Request                            $request,
//        OrderEnterpriseCertificateRegister $register,
//        OrderLog                           $log,
//        \app\service\Order                 $orderSer,
//        OrderEnterpriseCompany $company
//    ){
//        /**
//         * 因为牵扯到补充数据库内容 所以需要用补充id来处理数据
//         */
//        $id = $request->get ('id');
//
//        if(empty($id)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);
//
//        //通过id查询证书编码 用证书编码查询证书详情
//        $cerCode = $company->getIdValueCer($id);
//
//        $result = $register->getCertificateCodeFindData($cerCode);
//
//        //订单流程
//        $order_log = $log->getIdFindData ($id);
//
//        //收款信息
//        $result['collection'] = $orderSer->getTransaction($id,$this->Collection);
//
//        //付款信息
//        $result['payment'] = $orderSer->getTransaction($id,$this->Payment);
//
//        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,[
//            'data'=>$result,
//            'log'=>$order_log
//        ]);
//
//    }

    //公司需求删除
    public function delEnterPrise(
        Request                            $request,
        OrderEnterpriseCertificateRegister $certificateRegister,
        OrderEnterpriseCompany             $company,
        OrderDeal                          $deal,
        SystemOperateLog                   $systemOperateLogModel
    ){
        $id = $request->post('id');
        $uid = $request->post('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        //id转数组
        $idArr = explode(',', $id);

        //查询证书信息
        foreach ($idArr as $item) {
            $cerData = $certificateRegister->getWhereIdDataModel($item);

            //判断是否生成匹配证书
            if ($company->getCertificateCodeFindModel($cerData['certificate_code'])) {
                return ReJson(message::$ERROR_CODE, message::$ENTER_GENERATE_SUPPLEEMENT_DATA);
            }
            $systemOperateLogModel->addOperate($uid, message::$ORDER, '公司需求-删除' . $id);
            $certificateRegister->delIdData($item);
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }

    //公司证书删除
    public function delEnterDeal(
        Request                            $request,
        OrderEnterpriseCertificateRegister $certificateRegister,
        OrderEnterpriseCompany             $company,
        OrderDeal                          $deal,
        SystemOperateLog                   $systemOperateLogModel,
        RedisService                       $redisService
    ){
        $id = $request->post('id');
        $uid = $request->post('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        //id转数组
        $idArr = explode(',', $id);

        //查询证书信息
        foreach ($idArr as $item) {
            $cerData = $certificateRegister->getWhereIdDataModel($item);

            //判断是否有收付款
//            if ($deal->getCertificateIdFindModel($cerData['certificate_code'])) {
//                return ReJson(message::$ERROR_CODE, message::$ENTER_DEAL_DATA);
//            }

            $systemOperateLogModel->addOperate($uid, message::$ORDER, '公司证书-删除' . $id);
            $company->delIdData($item);
            $redisService->delPerformance($cerData);
            $redisService->delOrderDzData($cerData, 'order_gszs');
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }


    //公司证书匹配列表
    public function mateEnterPrise(Request $request, OrderPersonCertificateRegister $certificateRegister)
    {
        $page = $request->get('page') ?: 1;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $uid = $request->get('user_login_id');
        $certificate_id = $request->get('certificate_id');
        $sort = $request->get('sort') || '';//用于证书需求匹配的时候 按金钱字段排序

        $pages['total'] = $certificateRegister->getMateCount($this->CERTIFICATE_PERSON_STATUS);
        $pages['pageNumber'] = $pageNum;

        if ($sort == 'money') {//用于证书需求匹配的时候 按金钱字段排序
            $desc = 'catual_price DESC';
        } else {
            $desc = 'create_date DESC';
        }
        if (empty($certificate_id)) {
            $result = $certificateRegister->getWhereInDataList($this->CERTIFICATE_PERSON_STATUS, $pageNum, $page);
        } else {
            $result = $certificateRegister->getWhereCerInDataList($desc, $certificate_id, $this->CERTIFICATE_PERSON_STATUS, $pageNum, $page);
        }


        return ReJson(
            message::$SUCC_CODE,
            message::$SUCC_SELECT_DATA,
            ['data' => $result],
            $pages
        );
    }

    //获取第一步资料
    public function getDemand(
        Request                            $request,
        OrderPersonCertificateRegister     $person,
        OrderEnterpriseCertificateRegister $enterReg,
        Certificate                        $certificateSer,
        UserOrganization                   $organizationModel,
        System                             $systemService
    ){
        $person_code = $request->get('person_code');
        $enter_code = $request->get('enter_code');

        if (empty($person_code) || empty($enter_code)) {
            return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        }

        $result['enterInfo'] = $certificateSer->setCertificateDetails($enterReg->getEnterModel($enter_code));
        $result['personInfo'] = $person->getPersonModel($person_code);

        //有些身份证为空 手动补全参数返回
        if (!isset($result['personInfo'][0]['person_name'])) {
            $result['personInfo'][0]['person_name'] = '';
        }


        //type分割给前端 分割成 ，字符串
        if ($result['enterInfo'][0]['type'] == 3) {
            $result['enterInfo'][0]['type'] = [1, 2];
        } else {
            $result['enterInfo'][0]['type'] = [$result['enterInfo'][0]['type']];
        }
        //拼接公司部门人员id  销售人员
        if ($result['enterInfo'][0]['sale_uid']['id'] && $result['enterInfo'][0]['sale_org']['id']) {
            $str = $result['enterInfo'][0]['sale_uid']['id'] . ',';
            $str .= $systemService->getParentIdStr($result['enterInfo'][0]['sale_org']['id'], $organizationModel->getStructure());
            $result['enterInfo'][0]['sale_route_uid'] = array_map('intval', explode(',', rtrim($str, ',')));
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    //匹配第二步 提交人才证书资料
    public function subPersonInfo(
        Request                            $request,
        OrderEnterpriseCompany             $company,
        OrderEnterpriseCertificateRegister $enterpriseCertificateRegister,
        OrderPersonCertificateRegister     $personOrderModel,
        CluePerson                         $personModel,
        OrderLog                           $orderLog,
        OrderDeal                          $orderDeal,
        \app\service\Order                 $orderSer,
        Image                              $image,
        UserMessage                        $messageModel,
        Gateway                            $gateway,
        Certificate                        $certificateService,
        RedisService                       $redisService,
        SystemOperateLog                   $systemOperateLogModel
    ){
        $param = $request->post();

        $uid = $param['user_login_id'];

        if (empty($param['enter_id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        //人才证书id
        if (empty($param['person_id_card'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        //查询通知人是否填写
        if (empty($param['responsibility_uid'])) return ReJson(message::$ERROR_CODE, message::$ENTER_PERSON_RESPONSIBILITY_UID_EMPTY);
        //查询证书编号是否填写
        if (empty($param['certificate_code'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);


        //修改订单编号
        $param['enter_certificate_code'] = $param['certificate_code'];

        $param['certificate_code'] = $certificateService->CertificateCodeCreate('QYZSZC');

        if (isset($param['reg_from_file'])) {
            $array = $image->handle($param['reg_from_file'], 'reg_from_file', 'reg_from_file_name');
            $param['reg_from_file'] = $array['reg_from_file'];
            $param['reg_from_file_name'] = $array['reg_from_file_name'];
        }
        //查询是否有此负责人

        //查询证书信息
        $cerData = $enterpriseCertificateRegister->getWhereIdDataModel($param['enter_id']);

        //判断是否存在该企业注册证书信息
        if (empty($cerData)) {
            return ReJson(message::$ERROR_CODE, message::$ENTER_NOT_FOUND);
        }

        //查询该证书是否还需要人数
        if ($cerData['people_num'] <= 0) {
            return ReJson(message::$ERROR_CODE, message::$ORDER_DEAL_NUM_MEET);
        }

        //计算提交业绩
        //获取收证价
//        if ($cerData['people_num'] == 0){
//            $cerData['people_num'] = 1;
//        }
        $getPrice = $cerData['price_unit'];

        $param['performance'] = $getPrice - $param['contract_price'];

        //业绩归属人
        if ($param['get_uid'] && $param['responsibility_uid']) {
            $paramGetUid = explode(',', $param['get_uid']);
            if (count($paramGetUid) < 2) {
                $param['performance_uid'] = $param['get_uid'] . ',' . $param['responsibility_uid'];
            }
        }
        //提交人
        $param['submit_id'] = $uid;

        $param['status'] = $this->regCerRankSuccStatus; //匹配完成状态

        Db::startTrans();
        try {
//            生成补充记录，人数减一
            $enterpriseCertificateRegister->peopleNumDecModel($param['enter_id']);
            //人才订单修改为匹配完成
            $personOrderModel->setIdCardStatus($param['person_id_card']);
            //修改人才为已售出
            $personModel->setIdCardStatus($param['person_id_card']);
            $personId = $personOrderModel->getPersonIdCardOrderModel($param['person_id_card'])['id'];
            $personData = $personOrderModel->getPersonIdCardOrderModel($param['person_id_card']);

            /**
             * 添加需求表字段到补充订单里去
             * 最后新增的需求 导致硬性拼接入库
             */

            $enterData = Db::table('order_enterprise_certificate_register')->where(['id' => $param['enter_id']])->find();
            $param['business_id'] = $enterData['business_id'];
            $param['sale_org'] = $enterData['sale_org'];
            $param['sale_uid'] = $enterData['sale_uid'];
            $param['reg_unit'] = $enterData['reg_unit'];
            $param['price_unit'] = $enterData['price_unit'];
            $param['certificate_id'] = $enterData['certificate_id'];
            $param['certificate_leixing'] = $enterData['certificate_leixing'];
            $param['certificate_leibie'] = $enterData['certificate_leibie'];
            $param['certificate_dengji'] = $enterData['certificate_dengji'];
            $param['certificate_zhuanye'] = $enterData['certificate_zhuanye'];
            $param['certificate_b'] = $enterData['certificate_b'];
            $param['social_security'] = $enterData['social_security'];
            $param['cycle'] = $enterData['cycle'];
            $param['project'] = $enterData['project'];
            $param['people_num'] = $enterData['people_num'];
            $param['type'] = $enterData['type'];
            $param['order_label'] = $enterData['order_label'];

            /**
             * 绑定证书审核资料信息
             */
            $information_file_arr = explode(',', $personData['information_file']);
            $information_file_str = '';
            foreach ($information_file_arr as $key => $v) {
                if (strpos($v, config('file.url')) !== false) {
                    $v = substr($v,strlen(config('file.url')));
                }
                $information_file_str .= $v.',';
            }
            $information_file_str =  rtrim($information_file_str,',');
            $param['person_information_file'] = $information_file_str;//$personData['information_file'];
            $param['person_information_file_name'] = $personData['information_file_name'];

            //生成订单补充记录
            $data = $company->addDataModel($param);

            //添加成交库
            //判断该证书关联人才是新出还是续出
//            $orderDeal->addOrderDataModel ([
//                'order_company_id'=>$data->id,
//                'certificate_code'=>$param['certificate_code'],
//                'status'=>$orderSer->getOrderStatus ($data->id,$param['certificate_code'])
//            ]);
            //添加订单日志
            $orderLog->addDataModel([
                'message' => message::$ORDER_REG_CER_PIPEI_WANCHENG,
                'order_company_id' => $data->id,
                'submit_id' => $request->param('user_login_id'),
                'certificate_code' => $param['certificate_code'],
            ]);

            //通知
            $messages = $messageModel->addOrderCompanyModel($param['certificate_code'], $param['responsibility_uid'], $uid, '', $data->id);
            $gateway->sendToUid($param['responsibility_uid'], json_encode($messages));

            //修改缓存
//            $redisService->updateOrderZsshData ($personId);
            $redisService->deleteOrderZsshData($personId);
            $redisService->delPersonData($personModel->getPersonIdCardInfo($param['person_id_card'])['id']);

            $systemOperateLogModel->addOperate($uid, message::$ORDER, '公司证书-匹配完成');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        return ReJson(message::$SUCC_CODE, message::$ENTER_MATE_INFO_SUPPLEMENT);
    }

    //获取第二步完整资料
    public function getSubUnit(
        Request                            $request,
        OrderEnterpriseCertificateRegister $register,
        OrderEnterpriseCompany             $company,
        Image                              $image
    )
    {
        $id = $request->get('id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $result = $company->getDetailsModel($id);

        $result = $image->handleList($result, ['reg_from_file']);

        //公示栏与资料部，前端需要 所以返回数组
        if ($result['type'] == 3) {
            $result['type'] = [1, 2];
        } else {
            $result['type'] = [$result['type']];
        }
        //计算收证价格
//        if ($result['people_num'] == 0) $result['people_num'] = 1;
        $result['get_price'] = $result['price_unit'];

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }


    //补充第三步 聘用单位资料
    //同步生成成交订单
    public function subUnitInfo(
        Request                            $request,
        OrderEnterpriseCompany             $company,
        OrderDeal                          $deal,
        OrderEnterpriseCertificateRegister $enterpriseCertificateRegister,
        OrderLog                           $orderLog,
        UnitInfo                           $unit,
        Gateway                            $gateway,
        \app\service\User                  $userService,
        User                               $userModel,
        \app\service\Order                 $orderSer,
        SystemOperateLog                   $systemOperateLogModel,
        RedisService                       $redisService
    ){
        $param = $request->post();

        if (empty($param['certificate_code']) || empty($param['id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $uid = $param['user_login_id'];
        Db::startTrans();
        try {
            //验证必填参数
            Validate(\app\validate\Order::class)->scene('supUnitInfo')->check($param);

            //判断是否提交聘用单位
            if (!empty($param['employ_unit_title'])) {
                //聘用单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['employ_unit_title'],
                    'contacts' => $param['employ_unit_name'],
                    'mobile' => $param['employ_unit_mobile'],
                    'type' => $this->employUnit
                ]);
            }
            //查询证书补充信息库资料
            $comData = $company->getIdCertificateCodeFindModel($param['id'], $param['certificate_code']);

            //查询企业证书需求资料
            $enterData = $enterpriseCertificateRegister->getCertificateCodeFindData($comData['enter_certificate_code']);

            //未查询到证书信息
            if (empty($comData) || empty($enterData)) return ReJson(message::$ERROR_CODE, message::$ENTER_SUB_UNIT_INFO_ERR);


            /**
             * 查看当前订单 成交记录是否 满员
             */

            //获取该订单成交数量
            //        $dealNum = $deal->getWhereCertificateCodeCount($enterData['certificate_code']);
            //
            //        if($enterData['people_num'] <= $dealNum){
            //            return ReJson (message::$ERROR_CODE,message::$ORDER_DEAL_NUM_MEET);
            //        }
            //
            //        //判断是否已经成交过此补充证书
            //        if($deal->getOrderCompanyIdFindModel($comData['id'],$enterData['certificate_code'])){
            //            return ReJson (message::$ERROR_CODE,message::$DEAL_REPEAT);
            //        }

            //判断证书信息是否已经补全
            //        if (!$orderService->determineMeetCondition ($cerData)){
            //            return ReJson (message::$ERROR_CODE,message::$ENTER_PRISE_FROM_FIELD_FALSE);
            //        }

            /**
             * 拼接成交库参数
             */
            //$data['status'] = $this->ORDER_DEAL_TYPE_ENTERPRISE;  //匹配订单的时候已经修改状态为已售出

            $data['certificate_code'] = $comData['certificate_code'];
            $data['order_company_id'] = $comData['id'];//证书补全库id

            /**
             * 数据库操作
             */
            //添加成交记录
            //查询是否已经成交
            if (empty($deal->getOrderCompanyIdFindModel($data['order_company_id'], $data['certificate_code']))) {

                //判断该证书关联人才是新出还是续出
                $deal->addOrderDataModel([
                    'order_company_id' => $data['order_company_id'],
                    'certificate_code' => $data['certificate_code'],
                    'status' => $orderSer->getOrderStatus($data['order_company_id'], $param['certificate_code'])
                ]);

//                $deal->addOrderDataModel($data);
            }
            //修改需求库减一  补充第二步已经减去
//            $enterpriseCertificateRegister->peopleNumDecModel($enterData['id']);

            //添加订单日志库
//            $orderLog->addDataModel([
//                'submit_id' => $request->param('user_login_id'),
//                'message' => message::$ORDER_ENPER_PRISE_CREATE,
//                'certificate_code' => $enterData['certificate_code'],
//                'order_company_id' => $comData['id']//证书补全库id
//            ]);

            //添加订单日志
            $orderLog->addDataModel([
                'message' => "补充订单信息",
                'order_company_id' => $comData['id'],
                'submit_id' => $request->param('user_login_id'),
                'certificate_code' => $param['certificate_code'],
            ]);

            //该订单状态改为 已售出
            //修改证书补全库资料
//            if ($comData['status']['id'] == 11) {
//                $param['status'] = 1;
            //添加销售日期
//                $param['sale_date'] = date('Y-m-d H:i:s');
            $company->editUnitInfoDataModel($param);
//            }

//            //发送全局成交信息
//            $gateway->sendToAll(json_encode([
//                'type' => 'deal',
//                'content' => $userService->getUidOrgTitle($enterData['submit_id']),
//                'nickname' => $userModel->getIdNickName($enterData['submit_id']),
//                'title' => date('Y-m-d H:i:s') . "成交了公司证书！"
//            ]));

            $redisService->delOrderDzData($comData, 'order_gszs');

            $systemOperateLogModel->addOperate($uid, message::$ORDER, '公司证书:' . $param['certificate_code'] . '补充聘用单位资料');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_OPERATE);

    }

    //获取已经成交的证书
    public function getCompanyList(
        Request                            $request,
        OrderEnterpriseCompany             $company,
        Power                              $power,
        Certificate                        $certificate,
        OrderDeal                          $deal,
        OrderEnterpriseCertificateRegister $certificateRegister,
        FinanceServer                      $financeServer,
        OrderDealChargeback                $chargebackModel,
        \app\service\User                  $userService,
        RedisService                       $redisService
    ){
        $aliasId = $request->get('aliasId');
        $page = $request->get('page') ?: 1;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $param = $request->get();
        $uid = $request->param('user_login_id');

        //根据条件查询用户范围
        $userData = $power->getUserDataRange($uid);
// print_r($userData);die;
        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        $dataId = $company->getCompanyListModel($userData, $page, $pageNum);

        //查询退单
        $chargebackData = $chargebackModel->getCharDataModel();
        if (!empty($chargebackData)) {
            foreach ($chargebackData as $chargebackDatum) {
                $tData = $company->getCompanyCerIdFindModel($chargebackDatum['order_company_id'], $chargebackDatum['certificate_code']);
                if ($tData) {
                    //判断个人还是管理 增加响应退单内容
                    $idArr = array_column($dataId, 'id');
                    if (in_array($tData['id'], $idArr)) {
//                    if ($chargebackDatum['performance'] > 0){
//                        $tData['performance'] = '-'.$chargebackDatum['performance'];
//                    }else{
//                        $tData['performance'] = $chargebackDatum['performance'];
//                    }

//                        $tData['create_date'] = $chargebackDatum['create_date'];
                        $tData['sale_date'] = $chargebackDatum['create_date'];
//                        $tData['tuidan'] = true;
//                        $tData['reason'] = $chargebackDatum['reason'];
//                        $tData['status'] = [
//                            'id' => 999,
//                            'text' => '退单完成'
//                        ];
                        $dataId[] = $tData;
                    }
                }
            }
        }

        $result = $redisService->getOrderReKeyDataList($dataId, $uid, 'order_gszs');

        //数组搜索
        $data = $financeServer->resultSearchHandle($param, ChargeBackDataList($result));
        $pages['total'] = count($data);
        $pages['pageNum'] = $pageNum;

        $returnData = page($data, $page, $pageNum, 'desc', 'sale_date');

        //使用模型转换器转换
        foreach ($returnData as &$value) {
            /**
             * 模糊不可见字段
             */
            //判断登录人是否是出证人的领导
            //判断登录人数据可见范围为总公司  或 登录人为出证人的领导
            $witnessLeader = false;
            //判断登录人是否是出证人的领导
            $is_leader = $userService->userIsLeaderUser($uid, $value['sale_uid']['id']);
            //判断登录人数据可见范围是否为总公司
            $powerService = new Power();
            //获取领导人的数据可见范围
            $data_range = $powerService->getUserDataRand($uid);
            if ($data_range == 1 || $is_leader) {
                $witnessLeader = true;
            }

            if (!$witnessLeader) {
                $value['employ_unit_title'] .= '**';
                $value['employ_unit_name'] .= '**';
                $value['employ_unit_mobile'] .= '**';
            }

            //表单定时器
            $dingshiqi = Db::table('user_message')->where([
                'b_id' => $value['certificate_code'],
                'is_executed' => 2,
                'type' => 7,
                'order_company_id' => $value['id']
            ])->find();

            if ($dingshiqi) {
                $value['dingshiqi'] = 1;
            } else {
                $value['dingshiqi'] = 0;
            }

        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA,
            [
                'data' => $returnData,
                'power' => $fieldListTree
            ]
            , $pages);
    }


    //公司证书编辑
    public function editEnterPriseCertificate(
        Request                            $request,
        OrderEnterpriseCertificateRegister $certificateRegister,
        OrderLog                           $log,
        Certificate                        $certificateSer,
        SystemOperateLog                   $systemOperateLogModel
    ){
        $param = $certificateSer->splitCer($request->post());
        $uid = $request->post('user_login_id');

        $information_file = $request->file('information_file');
        $contract_file = $request->file('contract_file');
        if (empty($param['id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //判断是否有文件上传
        if (!empty($information_file)) {
            $param['information_file'] = \think\facade\Filesystem::disk('public')->putFile('file', $information_file);
        }

        if (!empty($contract_file)) {
            $param['contract_file'] = \think\facade\Filesystem::disk('public')->putFile('file', $contract_file);
        }

        //去掉url http
        $str = "file/";

        if (!empty($param['contract_file'])) {
            $param['contract_file'] = strstr($param['contract_file'], $str);
        }
        if (!empty($param['information_file'])) {
            $param['information_file'] = strstr($param['information_file'], $str);
        }


        //更新创建时间
        $param['create_date'] = date('Y-m-d H:i:s');

        Db::startTrans();

        try {

            //查询该需求是不是已退回状态
            $find = $certificateRegister->getWhereIdDataModel($param['id']);
            if ($find['gz_status']['id'] == 3) {
                $param['gz_status'] = 1;
            }

            $certificateRegister->editDataModel($param);

            $log->addDataModel([
                'submit_id' => $request->param('user_login_id'),
                'message' => message::$ORDER_ENPER_PRISE_EDIT,
                'type' => $this->ORDER_LOG_ENTERPRISE_TYPE,
                'order_company_id' => $param['id']
            ]);

            $systemOperateLogModel->addOperate($uid, message::$ORDER, '公司证书-编辑');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    /********************************************************************查询已经成交的证书**************************************************/
    //查询已经成交的证书详情
    public function getCompanyDetails(
        Request                $request,
        OrderEnterpriseCompany $company,
        OrderLog               $log,
        \app\service\Order     $orderSer,
        OrderDeal              $deal,
        Image                  $image,
        \app\service\User      $userService
    ){
        $id = $request->get('id');
        $certificate_code = $request->get('certificate_code');
        $user_login_id = $request->get('user_login_id');

        if (empty($id) || empty($certificate_code)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $result['data'] = $company->getDetailsModel($id);

        if (empty($result['data'])) {
            return ReJson(message::$ERROR_CODE, message::$SELECT_CERTIFICATE_ERR);
        }

        //拼接订单类型
        $result['data']['order_status'] = $deal->getCerComIdFindModel($result['data']['id'], $result['data']['certificate_code']);

        //拼接补充公示资料
        //查询该订单公示资料
        $pubInfo = $deal->getsuppleInfo($id, $certificate_code);

        if (!empty($pubInfo)) {
            $result['data']['electronic_certificate_file_illustrate'] = $pubInfo['electronic_certificate_file_illustrate'];
            $result['data']['electronic_certificate_file'] = $pubInfo['electronic_certificate_file'];
            $result['data']['electronic_certificate_date'] = $pubInfo['electronic_certificate_date'];
            $result['data']['b_electronic_certificate_file_illustrate'] = $pubInfo['b_electronic_certificate_file_illustrate'];
            $result['data']['b_electronic_certificate_file'] = $pubInfo['b_electronic_certificate_file'];
            $result['data']['b_electronic_certificate_date'] = $pubInfo['b_electronic_certificate_date'];
            $result['data']['b_reg_electronic_certificate_date'] = $pubInfo['b_reg_electronic_certificate_date'];
            $result['data']['electronic_certificate_file_illustrate_name'] = $pubInfo['electronic_certificate_file_illustrate_name'];
            $result['data']['b_electronic_certificate_file_name'] = $pubInfo['b_electronic_certificate_file_name'];
        } else {
            $result['data']['electronic_certificate_file_illustrate'] = '';
            $result['data']['electronic_certificate_file'] = '';
            $result['data']['electronic_certificate_date'] = '';
            $result['data']['b_electronic_certificate_file_illustrate'] = '';
            $result['data']['b_electronic_certificate_file'] = '';
            $result['data']['b_electronic_certificate_date'] = '';
            $result['data']['b_reg_electronic_certificate_date'] = '';
            $result['data']['electronic_certificate_file_illustrate_name'] = '';
            $result['data']['b_electronic_certificate_file_name'] = '';
        }
        //订单流程
        $result['log'] = $log->getIdCertificateCodeModel($id, $certificate_code) ?: '';

        //收款信息
        $result['collection'] = $orderSer->getTransaction($id, $certificate_code, $this->Collection);

        //付款信息
        $result['payment'] = $orderSer->getTransaction($id, $certificate_code, $this->Payment);
        /**
         * 处理文件
         */
        $result['data'] = $image->handleList($result['data'], ['reg_from_file', 'electronic_certificate_file_illustrate', 'b_electronic_certificate_file', 'person_information_file']);
        //判断登录人数据可见范围为总公司  或 登录人为出证人的领导
        $witnessLeader = false;
        //判断登录人是否是出证人的领导
        $is_leader = $userService->userIsLeaderUser($user_login_id, $result['data']['sale_uid']['id']);
        //判断登录人数据可见范围是否为总公司
        $powerService = new Power();
        //获取领导人的数据可见范围
        $data_range = $powerService->getUserDataRand($user_login_id);
        if ($data_range == 1 || $is_leader) {
            $witnessLeader = true;
        }
        $result['data']['witnessLeader'] = $witnessLeader;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    //删除已经成交的订单
    public function delCompany(
        Request                            $request,
        OrderEnterpriseCompany             $company,
        OrderLog                           $log,
        OrderEnterpriseCertificateRegister $register,
        OrderDeal                          $deal,
        OrderPersonCertificateRegister     $personModel,
        SystemOperateLog                   $systemOperateLogModel,
        RedisService $redisService
    ){
        $id = $request->post('id');
        $uid = $request->post('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        Db::startTrans();
        try {

            //成交订单详情
            $data = $company->getDetailsModel($id);

            //查询order_deal是否成交
            if (!empty($deal->getOrderCompanyIdFindModel($id, $data['certificate_code']))) {
                return ReJson(message::$ERROR_CODE, message::$ENTER_DEAL_DATA);
            }

            $register->peopleNumIncModel($data['enter_id']);

            //修改人才状态为待出售
            $personModel->setIdCardStatus($data['person_id_card'], 1);

            $company->delIdData($id);
            //添加记录
            $log->addDataModel([
                'submit_id' => $request->param('user_login_id'),
                'message' => message::$ORDER_PERSON_COMPLETE_DELETE,
                'type' => $this->ORDER_LOG_ENTERPRISE_TYPE,
                'order_company_id' => $id
            ]);
            //更新财务报表业绩统计缓存
            $redisService->updateDateBetweenData($data['sale_date'],$data['sale_date']);
            $systemOperateLogModel->addOperate($uid, message::$ORDER, '公司证书-删除匹配订单');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }

    //编辑已经成交的订单
    public function editCompany(
        Request                $request,
        OrderEnterpriseCompany $company,
        OrderLog               $log,
        OrderDeal              $orderDeal,
        UnitInfo               $unit,
        Image                  $image,
        SystemOperateLog       $systemOperateLogModel,
        RedisService           $redisService,
        Certificate            $certificateSer
    )
    {
        $id = $request->post('id');
        $uid = $request->post('user_login_id');
        //拆分证书
        $param = $certificateSer->splitCer($request->post());

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //通过id查询证书编号
        $certificateOrderData = $company->getDetailsModel($id);
        $certificateCode = $certificateOrderData['certificate_code'];

        if (empty($certificateCode)) {
            return ReJson(message::$ERROR_CODE, message::$ERR);
        }

        Db::startTrans();
        try {

            if (isset($param['reg_from_file'])) {
                $array = $image->handle($param['reg_from_file'], 'reg_from_file', 'reg_from_file_name');
                $param['reg_from_file'] = $array['reg_from_file'];
                $param['reg_from_file_name'] = $array['reg_from_file_name'];
            }

            if ($param['person_information_file']) {
                $array = $image->handle($param['person_information_file'], 'person_information_file', 'person_information_file_name');
                $param['person_information_file'] = $array['person_information_file'];
                $param['person_information_file_name'] = $array['person_information_file_name'];
            }


            //如果存在收证&出证价格 并且业绩没有被财务修改过 重新计算业绩
            if ($param['price_unit'] && $param['contract_price']) {
                if ($certificateOrderData['ad_performance'] === 0) {
                    $param['performance'] = $param['price_unit'] - $param['contract_price'];
                }
            }
            //编辑订单资料
            $company->editCompanyModel($param);
            $status = 1;
            //公示资料补充
            $publicInfo = [];
//            if ($electronic_certificate_file_illustrate) {
//                $status=2;
//                $publicInfo['electronic_certificate_file_illustrate'] = \think\facade\Filesystem::disk ('public')->putFile ('topic', $electronic_certificate_file_illustrate);
//            }else{
//                $publicInfo['electronic_certificate_file_illustrate'] = $param['electronic_certificate_file_illustrate'] ?? '';
//                $publicInfo['electronic_certificate_file_illustrate_name'] = $param['electronic_certificate_file_illustrate_name'] ?? '';
//            }
//
//
//            if ($b_electronic_certificate_file) {
//                $status=2;
//                $publicInfo['b_electronic_certificate_file'] = \think\facade\Filesystem::disk ('public')->putFile ('topic', $b_electronic_certificate_file);
//            }else{
//                $publicInfo['b_electronic_certificate_file'] = $param['b_electronic_certificate_file'] ?? '';
//                $publicInfo['b_electronic_certificate_file_name'] = $param['b_electronic_certificate_file_name'] ?? '';
//            }
            if (isset($param['electronic_certificate_file_illustrate'])) {
                $array = $image->handle($param['electronic_certificate_file_illustrate'], 'electronic_certificate_file_illustrate', 'electronic_certificate_file_illustrate_name');
                $publicInfo['electronic_certificate_file_illustrate'] = $array['electronic_certificate_file_illustrate'];
                $publicInfo['electronic_certificate_file_illustrate_name'] = $array['electronic_certificate_file_illustrate_name'];
            }
            if (isset($param['b_electronic_certificate_file'])) {
                $array = $image->handle($param['b_electronic_certificate_file'], 'b_electronic_certificate_file', 'b_electronic_certificate_file_name');
                $publicInfo['b_electronic_certificate_file'] = $array['b_electronic_certificate_file'];
                $publicInfo['b_electronic_certificate_file_name'] = $array['b_electronic_certificate_file_name'];
            }

            //电子证书文件说明
            if (isset($param['electronic_certificate_file'])) {
                $status = 2;
                $publicInfo['electronic_certificate_file'] = $param['electronic_certificate_file'];
            }
            //电子证书有效期
            if (isset($param['electronic_certificate_date'])) {
                $status = 2;
                $publicInfo['electronic_certificate_date'] = $param['electronic_certificate_date'];
            }
            //b证电子证书文件说明
            if (isset($param['b_electronic_certificate_file_illustrate'])) {
                $status = 2;
                $publicInfo['b_electronic_certificate_file_illustrate'] = $param['b_electronic_certificate_file_illustrate'];
            }

            //b证有效期
            if (isset($param['b_electronic_certificate_date'])) {
                $status = 2;
                $publicInfo['b_electronic_certificate_date'] = $param['b_electronic_certificate_date'];
            }

            //注册到期时间
            if (isset($param['b_reg_electronic_certificate_date'])) {
                $status = 2;
                $publicInfo['b_reg_electronic_certificate_date'] = $param['b_reg_electronic_certificate_date'];
            }
//            //文件名称
//            if (isset($param['electronic_certificate_file_illustrate_name'])){
//                $status=2;
//                $publicInfo['electronic_certificate_file_illustrate_name'] = $param['electronic_certificate_file_illustrate_name'];
//            }
//            //文件名称
//            if (isset($param['b_electronic_certificate_file_name'])){
//                $status=2;
//                $publicInfo['b_electronic_certificate_file_name'] = $param['b_electronic_certificate_file_name'];
//            }

            //先编辑
            $orderDeal->editIdCerDataModel($id, $certificateCode, $publicInfo);
            //查询公示资料是否已全部填写
//            $gsData = $orderDeal->getOrderCompanyIdFindModel($id, $certificateCode);

            $exData = $company->getWhereIdOrderByCreateData($param['id']);

//            if (!empty($gsData['electronic_certificate_file_illustrate']) &&
//                !empty($gsData['electronic_certificate_date'])
////                !empty($gsData['b_reg_electronic_certificate_date'])//证书到期时间
//            ){
//                //判断是否有B证
//                if (!empty($exData['certificate_b']['id']) && $exData['certificate_b']['id'] < 998) {
//                    if (!empty($gsData['b_electronic_certificate_date']) &&
//                        !empty($gsData['b_electronic_certificate_file'])){
//
//                        //查询当前订单状态
//                        $orderStatus = $company->getIdStatusModel($param['id']);
//                        if ($orderStatus === 1 || $orderStatus === 5){
//                            //修改订单为证书注册完成
//                            $company->certificateRegModel($param['id']);
//
//                            $log->addDataModel([
//                                'submit_id' => $request->param('user_login_id'),
//                                'message' => message::$ORDER_CERTIFICATE_REG_DEAL,
//                                'certificate_code' => $exData['certificate_code'],
//                                'order_company_id' => $param['id']
//                            ]);
//                        }
//                    }
//                }else{
//                    //查询当前订单状态
//                    $orderStatus = $company->getIdStatusModel($param['id']);
//
//                    if ($orderStatus === 1){
//                        //修改订单为证书注册完成
//                        $company->certificateRegModel($param['id']);
//
//                        $log->addDataModel([
//                            'submit_id' => $request->param('user_login_id'),
//                            'message' => message::$ORDER_CERTIFICATE_REG_DEAL,
//                            'certificate_code' => $exData['certificate_code'],
//                            'order_company_id' => $param['id']
//                        ]);
//                    }
//                }
//            }

            //判断是否提交注册单位
            if (!empty($param['reg_unit'])) {
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['reg_unit'],
                    'type' => $this->regUnit
                ]);
            }

            //判断是否提交聘用单位
            if (!empty($param['employ_unit_title'])) {
                //聘用单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['employ_unit_title'],
                    'contacts' => $param['employ_unit_name'],
                    'mobile' => $param['employ_unit_mobile'],
                    'type' => $this->employUnit
                ]);
            }

            //判断是否提交出证单位
            if (!empty($param['out_org'])) {
                //出证单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['out_org'],
                    'type' => $this->pushUnit
                ]);
            }

//            //查询当前订单状态
//            $orderStatus = $company->getIdStatusModel($param['id']);
//            if ($orderStatus === 1){
//                if ($status === 2){
//                    //修改订单为证书注册完成
//                    $company->certificateRegModel($param['id']);
//
//                    $log->addDataModel([
//                        'submit_id' => $request->param('user_login_id'),
//                        'message' => message::$ORDER_CERTIFICATE_REG_DEAL,
//                        'certificate_code' => $certificateCode,
//                        'order_company_id' => $param['id']
//                    ]);
//                }
//            }
            //删除业绩总表缓存
            $redisService->delPerformance($exData);
            //删除订单缓存
            $redisService->delOrderDzData($exData, 'order_gszs');
            $systemOperateLogModel->addOperate($uid, message::$ORDER, '公司证书-编辑订单：' . $certificateCode);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);

    }

    /*****************************************************************证书注册 倒证*****************************************************************************/

    //证书注册 倒证列表
    public function getEnterPriseCerInvertedEvidenceList(
        Request                 $request,
        Power                   $power,
        OrderEnterpriseExchange $exchange,
        OrderCertReverseCase    $orderCertReverseCase,
        \app\service\Order      $orderSer,
        \app\service\Publicity  $publicity,
        FinanceServer           $financeServer,
        OrderDealChargeback     $chargebackModel,
        RedisService            $redisService,
        \app\service\User       $userService
    ){
        $aliasId = $request->get('aliasId');
        $page = $request->get('page') ?: 1;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $uid = $request->param('user_login_id');
        $param = $request->get();

        //数据可见范围
        $userData = $power->getUserDataRange($uid);

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //字段权限
        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        $validate = new \app\validate\OrderCertReverseCase();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }
        $flag = flagStatus($param);
        $ids = $orderCertReverseCase->spliceWhere($param);

        $ids = !$ids ? [0] : $ids;
        $all_ids = $exchange->getExchangeListIds($userData);
        $ids = handlePersonIds($all_ids, $ids, $flag);

        //订单Id certificate_code sale_date
        $dataId = $exchange->getExchangeLIstIdModel($ids);

//        $result = $exchange->getExchangeListModel($page, $pageNum, $ids);

        /**
         * 查询退单 拼接退单ID certificate_code sale_date
         */
        $chargebackData = $chargebackModel->getCharDataModel();
        if (!empty($chargebackData)) {
            foreach ($chargebackData as $chargebackDatum) {
                $tData = $exchange->getWhereCerFieldDataModel($chargebackDatum['certificate_code'], 'id,certificate_code');
                if ($tData) {
                    //判断个人还是管理 增加响应退单内容
                    $idArr = array_column($dataId, 'id');
                    if (in_array($tData['id'], $idArr)) {
//                    if ($chargebackDatum['performance'] > 0){
//                        $tData['performance'] = '-'.$chargebackDatum['performance'];
//                    }else{
//                        $tData['performance'] = $chargebackDatum['performance'];
//                    }

//                        $tData['create_date'] = $chargebackDatum['create_date'];
                        $tData['sale_date'] = $chargebackDatum['create_date'];
//                        $tData['tuidan'] = true;
//                        $tData['reason'] = $chargebackDatum['reason'];
//                        $tData['status'] = [
//                            'id' => 999,
//                            'text' => '退单完成'
//                        ];
                        $dataId[] = $tData;
                    }
                }
            }
        }

//        //获取公式资料
//        $data = $publicity->getPublicyInfo($result,$uid);

        $data = $redisService->getOrderReKeyDataList($dataId, $uid);

        //基础条件过库查询 where条件数组查询
        $where['start_performance'] = $param['start_performance'] ?? '';
        $where['end_performance'] = $param['end_performance'] ?? '';
        $where['start_sale_date'] = $param['start_sale_date'];
        $where['end_sale_date'] = $param['end_sale_date'];
        $where['c_status'] = $param['c_status'] ?? '';
        $where['order_status'] = $param['status'] ?? '';
        $where['info_generate_status'] = $param['info_generate_status'] ?? '';

        //处理搜索条件
        $data = $financeServer->resultSearchHandle($where, ChargeBackDataList($data));

        $returnData = page($orderSer->whDingshiqi($data), $page, $pageNum, 'desc', 'sale_date');

        foreach ($returnData as &$datum) {

            /**
             * 模糊不可见字段
             */
            //判断登录人是否是出证人的领导
            $witnessLeader = $userService->userIsLeaderUser($uid, $datum['out_uid']['id']);
            //判断登录人是否是收证人的领导
            $rcipientLeader = $userService->userIsLeaderUser($uid, $datum['get_uid']['id']);
            //判断登录人数据可见范围是否为总公司
            $powerService = new Power();
            //获取领导人的数据可见范围
            $user_login_data_range = $powerService->getUserDataRand($uid);
            $headquarters = false;
            if ($user_login_data_range == 1) {
                $headquarters = true;
            }

            if (!$witnessLeader && !$headquarters) { //聘用单位
                $datum['employ_unit_title'] .= '**';
                $datum['employ_unit_name'] .= '**';
            }

            if (!$rcipientLeader && !$headquarters) {//供证单位
                $datum['out_unit'] .= '**';
                $datum['out_name'] .= '**';
                $datum['out_mobile'] .= '**';
            }
        }
        $pages['total'] = count($data);
        $pages['pageNum'] = $pageNum;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            //查询表单是否有定时器
            'data' => $returnData,
            'power' => $fieldListTree
        ], $pages);
    }

    //个人倒证列表
    public function getThatPersonEnterPriseCerInvertedEvidenceList(
        Request                            $request,
        Power                              $power,
        OrderEnterpriseCertificateRegister $reg,
        OrderEnterpriseExchange            $exchange,
        \app\service\Order                 $orderSer,
        OrderCertReverseCase               $orderCertReverseCase,
        \app\service\Publicity             $publicity,
        FinanceServer                      $financeServer,
        OrderDealChargeback                $chargebackModel,
        RedisService                       $redisService
    )
    {
        $aliasId = $request->get('aliasId');
        $page = $request->get('page') ?: 0;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $uid = $request->get('user_login_id');

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        $param = $request->get();
        $validate = new \app\validate\OrderCertReverseCase();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }

        $flag = flagStatus($param);
        $ids = $orderCertReverseCase->spliceWhere($param);
        $ids = !$ids ? [0] : $ids;
        $all_ids = $exchange->getOtherExchangeListIds($uid);
        $ids = handlePersonIds($all_ids, $ids, $flag);

        //获取个人提交倒证 getOrderIsOp 判断是否有退单|注销
        $dataId = $exchange->getExchangeIdListModel($uid, $ids);

        /**
         * 查询退单 拼接退单ID certificate_code sale_date
         */
        $chargebackData = $chargebackModel->getCharDataModel();
        if (!empty($chargebackData)) {
            foreach ($chargebackData as $chargebackDatum) {
                $tData = $exchange->getWhereCerFieldDataModel($chargebackDatum['certificate_code'], 'id,certificate_code');
                if ($tData) {
                    //判断个人还是管理 增加响应退单内容
                    $idArr = array_column($dataId, 'id');
                    if (in_array($tData['id'], $idArr)) {
//                    if ($chargebackDatum['performance'] > 0){
//                        $tData['performance'] = '-'.$chargebackDatum['performance'];
//                    }else{
//                        $tData['performance'] = $chargebackDatum['performance'];
//                    }

//                        $tData['create_date'] = $chargebackDatum['create_date'];
                        $tData['sale_date'] = $chargebackDatum['create_date'];
//                        $tData['tuidan'] = true;
//                        $tData['reason'] = $chargebackDatum['reason'];
//                        $tData['status'] = [
//                            'id' => 999,
//                            'text' => '退单完成'
//                        ];
                        $dataId[] = $tData;
                    }
                }
            }
        }

//        $datas = $exchange->getOtherExchangeListModel($uid, $page, $pageNum, $ids);

        //查询退单
//        $chargebackData = $chargebackModel->getCharDataModel();
//
//        if (!empty($chargebackData)){
//            foreach ($chargebackData as $chargebackDatum) {
//                $tData = $exchange->getFinanceFieldFindModel($chargebackDatum['certificate_code']);
//                if ($tData) {
//                    //判断个人还是管理 增加响应退单内容
//                    $idArr = array_column ($datas, 'id');
//                    if (in_array ($tData['id'], $idArr)) {
////                        if ($chargebackDatum['performance'] > 0){
////                            $tData['performance'] = '-'.$chargebackDatum['performance'];
////                        }else{
//                        $tData['performance'] = $chargebackDatum['performance'];
////                        }
//
//                        $tData['create_date'] = $chargebackDatum['create_date'];
//                        $tData['sale_date'] = $chargebackDatum['create_date'];
//                        $tData['tuidan'] = true;
//                        $tData['reason'] = $chargebackDatum['reason'];
//                        $tData['status'] = [
//                            'id' => 999,
//                            'text' => '退单完成'
//                        ];
//                        $datas[] = $tData;
//                    }
//                }
//            }
//        }

//        $result = $publicity->getPublicyInfo($orderSer->getOrderIsOp($datas),$uid);
        //基础条件过库查询 其他条件数组查询
        $where['start_performance'] = $param['start_performance'] ?? '';
        $where['end_performance'] = $param['end_performance'] ?? '';
        $where['start_sale_date'] = $param['start_sale_date'] ?? '';
        $where['end_sale_date'] = $param['end_sale_date'] ?? '';
        $where['c_status'] = $param['c_status'] ?? '';
        $where['order_status'] = $param['status'] ?? '';
        $where['info_generate_status'] = $param['info_generate_status'] ?? '';
        $where['person_name'] = $param['person_name'] ?? '';

        //处理搜索条件
        $result = $orderSer->getOrderIsOp($redisService->getOrderReKeyDataList($dataId, $uid));
        $data = $financeServer->resultSearchHandle($where, ChargeBackDataList($result));

        $pages['total'] = count($data);
        $pages['pageNum'] = $pageNum;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => page($orderSer->whDingshiqi($data, 'dz'), $page, $pageNum, 'desc', 'sale_date'),
            'power' => $fieldListTree
        ], $pages);
    }

    //证书注册 倒证详情
    public function getEnterPriseCerInvertedEvidenceDetails(
        Request                 $request,
        OrderEnterpriseExchange $reg,
        OrderLog                $log,
        \app\service\Order      $orderSer,
        Clue                    $clue,
        Certificate             $certificateSer,
        OrderDeal               $orderDeal,
        User                    $userModel,
        UserOrganization        $organizationModel,
        Image                   $image,
        \app\service\User       $userService
    )
    {
        $id = $request->get('id');
        $user_login_id = $request->get('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $data = $reg->getWhereIdOrderByCreateData($id);

        if (empty($data)) return ReJson(message::$ERROR_CODE, message::$SELECT_CERTIFICATE_DZ_ERR);

        //赋值收证人 收证部门 默认是第一步通知人
        if (is_array($data['get_uid'])) {
            if (!$data['get_uid']['id']) {
                $data['get_uid'] = $data['notice_id'];
                //部门
                $data['get_org']['id'] = $userModel->getUidOrgId($data['get_uid']['id']);
                $data['get_org']['text'] = $organizationModel->getStructureName($data['get_org']['id']);
            }
        }

        //倒证内容
//        $data = $certificateSer->DzDetailsSup($data);
        //拼接公示资料

        $result = $orderDeal->getsuppleInfo($data['id'], $data['certificate_code']);

        if (empty($result)) {
            $data['electronic_certificate_file_illustrate'] = '';
            $data['electronic_certificate_file'] = '';
            $data['electronic_certificate_date'] = '';
            $data['b_electronic_certificate_file_illustrate'] = '';
            $data['b_electronic_certificate_date'] = '';
            $data['b_electronic_certificate_file'] = '';
            $data['b_reg_electronic_certificate_date'] = '';
            $data['electronic_certificate_file_illustrate_name'] = '';
            $data['b_electronic_certificate_file_name'] = '';
            $data['order_status'] = '';
        } else {
            $result = $result->toArray();
            $data['electronic_certificate_file_illustrate'] = $result['electronic_certificate_file_illustrate'] ?: '';
            $data['electronic_certificate_file'] = $result['electronic_certificate_file'] ?: '';
            $data['electronic_certificate_date'] = $result['electronic_certificate_date'] ?: '';
            $data['b_electronic_certificate_file_illustrate'] = $result['b_electronic_certificate_file_illustrate'] ?: '';
            $data['b_electronic_certificate_date'] = $result['b_electronic_certificate_date'] ?: '';
            $data['b_electronic_certificate_file'] = $result['b_electronic_certificate_file'] ?: '';
            $data['b_reg_electronic_certificate_date'] = $result['b_reg_electronic_certificate_date'] ?: '';
            $data['electronic_certificate_file_illustrate_name'] = $result['electronic_certificate_file_illustrate_name'] ?: '';
            $data['b_electronic_certificate_file_name'] = $result['b_electronic_certificate_file_name'] ?: '';
            if (is_array($result['order_status'])) {
                $data['order_status'] = $result['order_status']['text'];
            } else {
                $data['order_status'] = $result['order_status'];
            }
        }
        $resu['data'] = $data;

        //收款信息
        $resu['collection'] = $orderSer->getTransaction($id, $resu['data']['certificate_code'], $this->Collection);

        //付款信息
        $resu['payment'] = $orderSer->getTransaction($id, $resu['data']['certificate_code'], $this->Payment);

        $resu['data'] = $image->handleList($resu['data'], ['reg_file', 'info_file', 'other_file', 'electronic_certificate_file_illustrate', 'b_electronic_certificate_file']);


        //判断登录人是否是出证人的领导
        $witnessLeader = $userService->userIsLeaderUser($user_login_id, $resu['data']['out_uid']['id']);
        //判断登录人是否是收证人的领导
        $rcipientLeader = $userService->userIsLeaderUser($user_login_id, $resu['data']['get_uid']['id']);
        //判断登录人数据可见范围是否为总公司
        $powerService = new Power();
        //获取领导人的数据可见范围
        $user_login_data_range = $powerService->getUserDataRand($user_login_id);
        $headquarters = false;
        if ($user_login_data_range == 1) {
            $headquarters = true;
        }

        $resu['data']['witnessLeader'] = $witnessLeader;
        $resu['data']['rcipientLeader'] = $rcipientLeader;
        $resu['data']['headquarters'] = $headquarters;

        //订单流程
        $order_log = $log->getIdCertificateCodeModel($id, $resu['data']['certificate_code']);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => $resu,
            'log' => $order_log
        ]);
    }

    /**
     * 倒证详情点击信息生成
     * @param Request $request
     * @param OrderService $orderService
     * @return false|string
     */
    public function reverseCaseInfoGenerate(Request $request, OrderService $orderService, OrderLog $log)
    {
        try {
            $id = $request->post('id');
            $certificate_code = $request->post('certificate_code');
            if (!$certificate_code || !$id) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
            $orderService->clickInfoGenerate($id, $certificate_code);
            //添加日誌
            $log->addDataModel([
                'submit_id' => $request->param('user_login_id'),
                'message' => '信息生成',
                'certificate_code' => $certificate_code,
                'order_company_id' => $id
            ]);
            return ReJson(message::$SUCC_CODE, '信息生成成功');
        } catch (\Exception $exception) {
            return ReJson(message::$ERROR_CODE, $exception->getMessage());
        }
    }

    public function registerOver(Request $request, OrderService $orderService, OrderLog $log, OrderEnterpriseExchange $orderEnterpriseExchangeModel)
    {
        try {
            $id = $request->post('id');
            if (!$id) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
            $orderService->registerOver($id);
            $data = $orderEnterpriseExchangeModel->getIdDataModel($id);
            //添加日誌
            $log->addDataModel([
                'submit_id' => $request->param('user_login_id'),
                'message' => message::$ORDER_CERTIFICATE_REG_DEAL,
                'certificate_code' => $data['certificate_code'],
                'order_company_id' => $id
            ]);
            return ReJson(message::$SUCC_CODE, '注册完成');
        } catch (\Exception $exception) {
            return ReJson(message::$ERROR_CODE, $exception->getMessage());
        }
    }

    //编辑倒证
    public function editEnterPriseInvertedEvidenceData(
        Request                 $request,
        OrderEnterpriseExchange $reg,
        OrderLog                $log,
        Certificate             $certificateSer,
        OrderDeal               $orderDeal,
        UnitInfo                $unit,
        Image                   $image,
        SystemOperateLog        $systemOperateLogModel,
        RedisService            $redisService,
        CluePerson $personModel
    )
    {
        $param = $certificateSer->splitCer($request->post());
        $uid = $request->post('user_login_id');

        $info_file = $request->file('info_file');
        $reg_file = $request->file('reg_file');
        //是否有文件上传
        $electronic_certificate_file_illustrate = $request->file('electronic_certificate_file_illustrate');
        $b_electronic_certificate_file = $request->file('b_electronic_certificate_file');
        $other_file = $request->file('other_file'); //其他资料文件
        if (empty($param['id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //通过id查询证书编号
        $certificateData = $reg->getWhereIdOrderByCreateData($param['id']);

        //去掉url http
        $str = "file/";

//        if (!empty($param['info_file'])){
//            $param['info_file'] = strstr($param['info_file'],$str);
//        }
//        if (!empty($param['reg_file'])){
//            $param['reg_file'] = strstr($param['reg_file'],$str);
//        }

//        //判断是否有文件上传
//        if(!empty($info_file)){
//            $param['info_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $info_file);
//        }
//
//        if (!empty($reg_file)){
//            $param['reg_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $reg_file);
//        }
//        if (!empty($other_file)){
//            $param['other_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $other_file);
//        }
        if (isset($param['info_file'])) {
            $array = $image->handle($param['info_file'], 'info_file', 'info_file_name');
            $param['info_file'] = $array['info_file'];
            $param['info_file_name'] = $array['info_file_name'];
        }

        if (isset($param['reg_file'])) {
            $array = $image->handle($param['reg_file'], 'reg_file', 'reg_file_name');
            $param['reg_file'] = $array['reg_file'];
            $param['reg_file_name'] = $array['reg_file_name'];
        }

        if (isset($param['other_file'])) {
            $array = $image->handle($param['other_file'], 'other_file', 'other_file_name');
            $param['other_file'] = $array['other_file'];
            $param['other_file_name'] = $array['other_file_name'];
        }

        Db::startTrans();
        try {
            //查询倒证资料
            $exData = $reg->getWhereIdOrderByCreateData($param['id']);
            //计算业绩提交入库
            if (!$exData['out_price']) {
                $exData['out_price'] = 0;
            }
            if (!$param['get_price']) {
                $param['get_price'] = 0;
            }
            //ad_performance=0 修改业绩
            if ($exData['ad_performance'] == 0) {
                //计算该订单业绩
                if (isset($param['out_price']) && !empty($param['out_price'])) {
                    $param['performance'] = $param['out_price'] - $param['get_price'] ?: 0;
                } else {
                    $param['performance'] = $exData['out_price'] - $param['get_price'] ?: 0;
                }
            }


            //业绩归属人
            if ($param['get_uid']) {
                $performanceIdArr = explode(',', $exData['performance_uid']);

                if (count($performanceIdArr) < 2) {
                    if (!in_array($param['get_uid'], $performanceIdArr)) {
                        $param['performance_uid'] = implode(',', $performanceIdArr);
                        $param['performance_uid'] .= ',' . $param['get_uid'];

                    }
                }
            }
            /**
             * 验证入库参数
             */

            Validate(\app\validate\Certificate::class)->scene('editExchangeCertificate')->check($param);

            $reg->editDataModel($param);
            //公示资料补充
            $publicInfo = [];

            if (isset($param['electronic_certificate_file_illustrate'])) {
                $array = $image->handle($param['electronic_certificate_file_illustrate'], 'electronic_certificate_file_illustrate', 'electronic_certificate_file_illustrate_name');
                $publicInfo['electronic_certificate_file_illustrate'] = $array['electronic_certificate_file_illustrate'];
                $publicInfo['electronic_certificate_file_illustrate_name'] = $array['electronic_certificate_file_illustrate_name'];
            }

            if (isset($param['b_electronic_certificate_file'])) {
                $array = $image->handle($param['b_electronic_certificate_file'], 'b_electronic_certificate_file', 'b_electronic_certificate_file_name');
                $publicInfo['b_electronic_certificate_file'] = $array['b_electronic_certificate_file'];
                $publicInfo['b_electronic_certificate_file_name'] = $array['b_electronic_certificate_file_name'];
            }

//            //电子证书文件说明
            if (!empty($param['electronic_certificate_file'])) {
//                $status = 2;//证书注册完成
                $publicInfo['electronic_certificate_file'] = $param['electronic_certificate_file'];
            }
//            //电子证书有效期
            if (!empty($param['electronic_certificate_date'])) {
//                $status = 2;//证书注册完成
                $publicInfo['electronic_certificate_date'] = $param['electronic_certificate_date'];
            } else {
                $publicInfo['electronic_certificate_date'] = null;
            }
//            //b证电子证书文件说明
            if (!empty($param['b_electronic_certificate_file_illustrate'])) {
//                $status = 2;//证书注册完成
                $publicInfo['b_electronic_certificate_file_illustrate'] = $param['b_electronic_certificate_file_illustrate'];
            }
//
//            //b证有效期
            if (!empty($param['b_electronic_certificate_date'])) {
//                $status = 2;//证书注册完成
                $publicInfo['b_electronic_certificate_date'] = $param['b_electronic_certificate_date'];
            } else {
                $publicInfo['b_electronic_certificate_date'] = null;
            }
//
//            //注册到期时间
            if (!empty($param['b_reg_electronic_certificate_date'])) {
//                $status = 2;//证书注册完成
                $publicInfo['b_reg_electronic_certificate_date'] = $param['b_reg_electronic_certificate_date'];
            } else {
                $publicInfo['b_reg_electronic_certificate_date'] = null;
            }

            //查询公示资料是否已全部填写
            $gsData = $orderDeal->getOrderCompanyIdFindModel($param['id'], $certificateData['certificate_code']);

            $exData = $certificateData;

//            if (!empty($gsData['electronic_certificate_file_illustrate']) &&
//                !empty($gsData['electronic_certificate_date'])
////                !empty($gsData['b_reg_electronic_certificate_date'])//证书到期时间
//            ){
//                //判断是否有B证
//                if (!empty($exData['certificate_b']['id']) && $exData['certificate_b']['id'] < 998){
//                    if (!empty($gsData['b_electronic_certificate_date']) &&
//                        !empty($gsData['b_electronic_certificate_file'])){
//
//                        //查询当前订单状态
//                        $orderStatus = $reg->getIdStatusModel($param['id']);
//                        if ($orderStatus === 1 || $orderStatus === 5){
//                            //修改订单为证书注册完成
//                            $reg->certificateRegModel($param['id']);
//
//                            $log->addDataModel([
//                                'submit_id' => $request->param('user_login_id'),
//                                'message' => message::$ORDER_CERTIFICATE_REG_DEAL,
//                                'certificate_code' => $exData['certificate_code'],
//                                'order_company_id' => $param['id']
//                            ]);
//                        }
//                    }
//                }else{
//                    //查询当前订单状态
//                    $orderStatus = $reg->getIdStatusModel($param['id']);
//
//                    if ($orderStatus === 1){
//                        //修改订单为证书注册完成
//                        $reg->certificateRegModel($param['id']);
//
//                        $log->addDataModel([
//                            'submit_id' => $request->param('user_login_id'),
//                            'message' => message::$ORDER_CERTIFICATE_REG_DEAL,
//                            'certificate_code' => $exData['certificate_code'],
//                            'order_company_id' => $param['id']
//                        ]);
//                    }
//                }
//            }


            //判断是否提交注册单位
            if (!empty($param['unit_reg_title'])) {
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['unit_reg_title'],
                    'type' => $this->regUnit
                ]);
            }
            //判断是否提交注册单位
            if (!empty($param['reg_unit'])) {
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['reg_unit'],
                    'type' => $this->regUnit
                ]);
            }

            //判断是否提交聘用单位
            if (!empty($param['employ_unit_title'])) {
                //聘用单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['employ_unit_title'],
                    'contacts' => $param['employ_unit_name'],
                    'mobile' => $param['employ_unit_mobile'],
                    'type' => $this->employUnit
                ]);
            }

            //判断是否提交出证单位
            if (!empty($param['out_unit'])) {
                //出证单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['out_unit'],
                    'type' => $this->pushUnit
                ]);
            }
            //先编辑
            $orderDeal->editIdCerDataModel($exData['id'], $exData['certificate_code'], $publicInfo);
            //查询公示资料是否已全部填写
//            $gsData = $orderDeal->getOrderCompanyIdFindModel ($exData['id'],$exData['certificate_code']);

//            if (!empty($gsData['electronic_certificate_file_illustrate']) &&
//                !empty($gsData['electronic_certificate_date'])
////                !empty($gsData['b_reg_electronic_certificate_date'])//证书到期时间
//            ){
//
//                //判断是否有B证
//                if (!empty($exData['certificate_b']['id']) && $exData['certificate_b']['id'] < 998){
//
//                    if (!empty($gsData['b_electronic_certificate_date']) &&
//                        !empty($gsData['b_electronic_certificate_file'])){
//                        //查询当前订单状态
//                        $orderStatus = $reg->getIdStatusModel($param['id']);
//                        if ($orderStatus === 1){
//                            //修改订单为证书注册完成
//                            $reg->certificateRegModel($param['id']);
//
//                            $log->addDataModel([
//                                'submit_id' => $request->param('user_login_id'),
//                                'message' => message::$ORDER_CERTIFICATE_REG_DEAL,
//                                'certificate_code' => $exData['certificate_code'],
//                                'order_company_id' => $param['id']
//                            ]);
//                        }
//                    }
//                }else{
//
//                    //查询当前订单状态
//                    $orderStatus = $reg->getIdStatusModel($param['id']);
//                    if ($orderStatus === 1){
//                        //修改订单为证书注册完成
//                        $reg->certificateRegModel($param['id']);
//
//                        $log->addDataModel([
//                            'submit_id' => $request->param('user_login_id'),
//                            'message' => message::$ORDER_CERTIFICATE_REG_DEAL,
//                            'certificate_code' => $exData['certificate_code'],
//                            'order_company_id' => $param['id']
//                        ]);
//                    }
//                }
//            }

            //判断是否提交注册单位
            if (!empty($param['reg_unit'])) {
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['reg_unit'],
                    'type' => $this->regUnit
                ]);
            }

            //判断是否提交聘用单位
            if (!empty($param['employ_unit_title'])) {
                //聘用单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['employ_unit_title'],
                    'contacts' => $param['employ_unit_name'],
                    'mobile' => $param['employ_unit_mobile'],
                    'type' => $this->employUnit
                ]);
            }

            //判断是否提交出证单位
            if (!empty($param['out_org'])) {
                //出证单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['out_org'],
                    'type' => $this->pushUnit
                ]);
            }

            /**
             * 删除订单缓存
             */
            $redisService->delOrderDzData($certificateData, "order_dz");
            //删除业绩总表缓存
            $redisService->delPerformance($certificateData);
            //业绩统计
            $redisService->updateDateBetweenData(date('Y-m-d',strtotime($certificateData['sale_date'])),date('Y-m-d',strtotime($certificateData['sale_date'])));
            //删除人才库ID缓存
            $redisService->delPersonData ($personModel->getPersonIdCardInfo ($exData['id_card'])['id']);
            $systemOperateLogModel->addOperate($uid, message::$ORDER, '倒证-编辑');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_OPERATE);
    }

    //删除倒证
    public function delEnterPrisePriseCerInvertedEvidence(
        Request                 $request,
        OrderDeal               $deal,
        OrderEnterpriseExchange $exchange,
        SystemOperateLog        $systemOperateLogModel,
        RedisService            $redisService
    ){
        $id = $request->post('id');
        $uid = $request->post('user_login_id');
        //获取倒证订单id 查询成交库 有数据否定删除
//        if ($deal->getWhereFid($id)) {
//
//            return ReJson(message::$ERROR_CODE, message::$ERR_DELETE_ORDER_EXIST);
//        }

        //id转数组
        $idArr = explode(',', $id);

        //查询证书信息
        foreach ($idArr as $item) {
            $cerData = $exchange->getWhereIdOrderByCreateData($item);
            //判断是否有收付款
//            if ($deal->getCertificateIdFindModel($cerData['certificate_code'])) {
//                return ReJson(message::$ERROR_CODE, message::$ENTER_DEAL_DATA);
//            }

            $exchange->delIdModel($item);
            /**
             * 删除缓存库订单
             */
            $redisService->delOrderDzData($cerData, "order_dz");
            //删除业绩总表缓存
            $redisService->delPerformance($cerData);
            //更新财务报表业绩统计缓存
            $redisService->updateDateBetweenData($cerData['sale_date'],$cerData['sale_date']);
            $systemOperateLogModel->addOperate($uid, message::$ORDER, '倒证-删除' . $id);
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }

    //成交前获取资料
    public function getInvertedEvidenceInfo(Request $request, OrderEnterpriseExchange $exchange)
    {
        $id = $request->get('id');

        $result = $exchange->getWhereIdOrderByCreateData($id);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    // 成交倒证订单
    public function editEnterPriseCerInvertedEvidenceSubmit(
        OrderEnterpriseCertificateRegister $orderEnterpriseCertificateRegister,
        Request                            $request,
        OrderEnterpriseExchange            $Exchange,
        OrderDeal                          $deal,
        OrderLog                           $orderLog,
        User                               $user,
        Gateway                            $gateway,
        UnitInfo                           $unit,
        \app\service\User                  $userService,
        SystemOperateLog                   $systemOperateLogModel
    )
    {
        $param = $request->post();
        $uid = $request->post('user_login_id');

        if (empty($param['id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        /**
         * 查看当前订单 成交记录是否 满员
         */
        //查询订单信息
        $ExchangeData = $Exchange->getWhereIdOrderByCreateData($param['id']);
        $cerData = $orderEnterpriseCertificateRegister->getIdDataModel($ExchangeData['enter_id']);

        //获取该订单成交数量
        $dealNum = $deal->getWhereCertificateCodeCount($cerData['certificate_code']);

        if ($cerData['people_num'] <= $dealNum) {
            return ReJson(message::$ERROR_CODE, message::$ORDER_DEAL_NUM_MEET);
        }

        Db::startTrans();
        try {
            Validate(\app\validate\Certificate::class)->scene('exchangeCertificate')->check($param);

            //计算业绩提交入库
            if ($ExchangeData['ad_performance'] === 0) {
                $param['performance'] = $ExchangeData['out_price'] - $param['get_price'] ?: 0;
            }

            //业绩归属人
//            if($param['get_uid']){
//                $performanceIdArr = explode (',',$ExchangeData['performance_uid']);
//                if (count ($performanceIdArr) < 2){
//                    if (!in_array ($param['get_uid'],$performanceIdArr)){
//                        $param['performance_uid'] = implode (',',$performanceIdArr);
//                        $param['performance_uid'] .= ','.$param['get_uid'];
//
//                    }
//                }
//            }
            //补全倒证库资料
            $param['sale_date'] = date('Y-m-d H:i:s');
            $data = $Exchange->editEnterIdDataModel($param);

            //判断是否提交注册单位
            if (!empty($param['reg_unit'])) {
                //注册单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['reg_unit'],
                    'type' => $this->regUnit
                ]);
            }

            //判断是否提交聘用单位
            if (!empty($param['employ_unit_title'])) {
                //聘用单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['employ_unit_title'],
                    'contacts' => $param['employ_unit_name'],
                    'mobile' => $param['employ_unit_mobile'],
                    'type' => $this->employUnit
                ]);
            }

            //判断是否提交出证单位
            if (!empty($param['out_org'])) {
                //出证单位不为空 同步单位到单位资料库
                $unit->addDataModel([
                    'title' => $param['out_org'],
                    'type' => $this->pushUnit
                ]);
            }

            //添加成交记录
            $deal->addOrderDataModel([
                'certificate_code' => $cerData['certificate_code'],
                'status' => $this->ORDER_DEAL_STATUS,
                'type' => $this->ORDER_DEAL_TYPE_ENTERPRISE_DZ,
            ]);

            //生成订单日志
            $orderLog->addDataModel([
                'order_company_id' => $cerData['id'],
                'message' => message::$ORDER_ENPER_DZ_CJ,
//                'type'=>$this->ORDER_LOG_ENTERPRISE_BUSINESS,
                'certificate_code' => $cerData['certificate_code']
            ]);

            //发送全局成交
            $gateway->sendToAll(json_encode([
                'type' => 'deal',
                'content' => $userService->getUidOrgTitle($ExchangeData['submit_id']),
                'nickname' => $user->getIdNickName($ExchangeData['submit_id']),
                'title' => date('Y-m-d H:i:s') . "成交了倒证！"
            ]));

            $systemOperateLogModel->addOperate($uid, message::$ORDER, '倒证-成交');
            Db::commit();
        } catch (\Exception|ValidateException $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_ORDER_DEAL);
    }


    /*****************************************************************企业证书*****************************************************************************/

    //企业证书列表
    public function getEnterPriseCerList(
        Request                            $request,
        Power                              $power,
        OrderEnterpriseCertificateBusiness $enCre,
        \app\service\Order                 $orderSer,
        OrderEnterCert                     $orderEnterCert,
        FinanceServer                      $financeServer,
        OrderDealChargeback                $chargebackModel
    )
    {
        $aliasId = $request->get('aliasId');
        $page = $request->get('page') ?: 0;
        $uid = $request->get('user_login_id');
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        //根据条件查询用户范围
        $userData = $power->getUserDataRange($uid);

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        $param = $request->get();
        $validate = new \app\validate\OrderEnterCert();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }
        $flag = flagStatus($param);
        $ids = $orderEnterCert->spliceWhere($param);

        $ids = !$ids ? [0] : $ids;
        $all_ids = $enCre->getDataIds($userData);

        $ids = handlePersonIds($all_ids, $ids, $flag);
//        $ids[] = $request->get ('user_login_id'); //添加当前登陆人

        //getOrderIsOp 判断是否有退单或者注销状态
        $datas = $enCre->getDataModel($page, $pageNum, $ids);

        //查询退单
        $chargebackData = $chargebackModel->getCharDataModel();
        if (!empty($chargebackData)) {
            foreach ($chargebackData as $chargebackDatum) {
                $tData = $enCre->getCerDataModel($chargebackDatum['certificate_code']);
                //判断个人还是管理 增加响应退单内容
                $idArr = array_column($datas, 'id');
                if ($tData) {
                    if (in_array($tData['id'], $idArr)) {
//                        if ($chargebackDatum['performance'] > 0){
//                            $tData['performance'] = '-'.$chargebackDatum['performance'];
//                        }else{
                        $tData['performance'] = $chargebackDatum['performance'];
//                        }

                        $tData['create_date'] = $chargebackDatum['create_date'];
                        $tData['sale_date'] = $chargebackDatum['create_date'];
                        $tData['tuidan'] = true;
                        $tData['reason'] = $chargebackDatum['reason'];
                        $tData['status'] = [
                            'id' => 999,
                            'text' => '退单完成'
                        ];
                        $datas[] = $tData;
                    }
                }
            }
        }

        $result = $orderSer->getOrderIsOp($datas);

        $where['start_performance'] = $param['start_performance'] ?? '';
        $where['end_performance'] = $param['end_performance'] ?? '';
        $where['c_status'] = $param['status'];
        $where['start_sale_date'] = $param['sale_start_date'];
        $where['end_sale_date'] = $param['sale_end_date'];


        //条件筛选
        $result = $financeServer->resultSearchHandle($where, $result);

        $pages['total'] = count($result);
        $pages['pageNumber'] = $pageNum;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            //查询表单是否有定时器
            'data' => page($orderSer->whDingshiqi($result), $page, $pageNum, 'desc', 'sale_date'),
            'power' => $fieldListTree
        ], $pages);
    }

    //个人企业证书列表
    public function getThatPersonEnterPriseCerList(
        Request                            $request,
        Power                              $power,
        OrderEnterpriseCertificateBusiness $enCre,
        \app\service\Order                 $orderSer,
        OrderEnterCert                     $orderEnterCert,
        Image                              $image,
        FinanceServer                      $financeServer,
        OrderDealChargeback                $chargebackModel
    )
    {
        $aliasId = $request->get('aliasId');

        $page = $request->get('page') ?: 0;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;

        $uid = $request->get('user_login_id');

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        $param = $request->get();
        $validate = new \app\validate\OrderEnterCert();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }
        $flag = flagStatus($param);
        $ids = $orderEnterCert->spliceWhere($param);
        $ids = !$ids ? [0] : $ids;
        $all_ids = $enCre->getThatPersonDataIds($uid);
        $ids = handlePersonIds($all_ids, $ids, $flag);

        $ids[] = $request->get('user_login_id'); //添加当前登陆人

        $datas = $enCre->getThatPersonDataModel($uid, $ids, $page);

        //查询退单
        $chargebackData = $chargebackModel->getCharDataModel();

        if (!empty($chargebackData)) {
            foreach ($chargebackData as $chargebackDatum) {
                $tData = $enCre->getCerDataModel($chargebackDatum['certificate_code']);

                if ($tData) {
                    //判断个人还是管理 增加响应退单内容
                    $idArr = array_column($datas, 'id');
                    if (in_array($tData['id'], $idArr)) {
//                        if ($chargebackDatum['performance'] > 0){
//                            $tData['performance'] = '-'.$chargebackDatum['performance'];
//                        }else{
                        $tData['performance'] = $chargebackDatum['performance'];
//                        }

                        $tData['create_date'] = $chargebackDatum['create_date'];
                        $tData['sale_date'] = $chargebackDatum['create_date'];
                        $tData['tuidan'] = true;
                        $tData['reason'] = $chargebackDatum['reason'] ?: '';
                        $tData['status'] = [
                            'id' => 999,
                            'text' => '退单完成'
                        ];
                        $datas[] = $tData;
                    }
                }
            }
        }

        $result = $orderSer->getOrderIsOp($datas);
        $result = $image->handleList($result, ['contract_file', 'information_file'], true);
        $where['start_performance'] = $param['start_performance'] ?? '';
        $where['end_performance'] = $param['end_performance'] ?? '';
        $where['c_status'] = $param['status'];
        $where['start_sale_date'] = $param['sale_start_date'];
        $where['end_sale_date'] = $param['sale_end_date'];
        //条件筛选
        $results = $financeServer->resultSearchHandle($where, $result);

        $pages['total'] = count($results);
        $pages['pageNumber'] = $pageNum;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            //判断第二步是否填写完成&&定时器
            'data' => page($orderSer->whDingshiqi($results, 'qyzs'), $page, $pageNum, 'desc', 'sale_date'),
            'power' => $fieldListTree
        ], $pages);
    }

    //企业证书详情
    public function getEnterPriseCerBusinessDetails(
        Request                            $request,
        OrderEnterpriseCertificateBusiness $business,
        OrderLog                           $log,
        \app\service\Order                 $orderSer,
        Image                              $image
    )
    {
        $id = $request->get('id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //企业证书内容
        $result = $business->getWhereIdDataModel($id);
        if (empty($result)) return ReJson(message::$ERROR_CODE, message::$SELECT_CERTIFICATE_ERR);

        //获取订单日志
        $order_log = $log->getCertificateCodeFindDataModel($result['certificate_code']);
        //收款信息
        $collection = $orderSer->getCerTransaction($result['certificate_code'], $this->Collection);
        //付款信息
        $payment = $orderSer->getCerTransaction($result['certificate_code'], $this->Payment);
        //处理多文件上传问题
        $result = $image->handleList($result, ['information_file', 'contract_file']);
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => $result,
            'collection' => $collection,
            'payment' => $payment,
            'log' => $order_log
        ]);
    }

    //编辑企业证书
    public function editEnterPriseCer(
        Request                            $request,
        OrderEnterpriseCertificateBusiness $business,
        Certificate                        $certificateSer,
        OrderLog                           $orderLogModel,
        Image                              $image,
        SystemOperateLog                   $systemOperateLogModel,
        RedisService                       $redisService
    )
    {
        $param = $certificateSer->splitCer($request->post());
        $uid = $request->post('user_login_id');

        $information_file = $request->file('information_file');
        $contract_file = $request->file('contract_file');
        if (empty($param['id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //ad_performance=0 修改业绩
        $data = $business->getWhereIdDataModel($param['id']);
        if ($data['ad_performance'] == 0) {
            $param['performance'] = $param['sale_price'] - $param['cost_price'];
        }

        $array = $image->handle($param['contract_file'], 'contract_file', 'contract_file_name');
        $param['contract_file'] = $array['contract_file'];
        $param['contract_file_name'] = $array['contract_file_name'];
        $array = $image->handle($param['information_file'], 'information_file', 'information_file_name');
        $param['information_file'] = $array['information_file'];
        $param['information_file_name'] = $array['information_file_name'];
//        //判断是否有文件上传
//        if(!empty($information_file)){
//            $param['information_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $information_file);
//        }
//
//        if (!empty($contract_file)){
//            $param['contract_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $contract_file);
//        }
//
//        //去掉url http
//        $str = "file/";
//
//        if (!empty($param['contract_file'])){
//            $param['contract_file'] = strstr($param['contract_file'],$str);
//        }
//        if (!empty($param['information_file'])){
//            $param['information_file'] = strstr($param['information_file'],$str);
//        }

        try {
            $business->editDataModel($param);

            //查询证书编号
            $data = $business->getWhereIdDataModel($param['id']);
            //删除业绩总表缓存
            $redisService->delPerformance($data);
            //删除订单缓存
            $redisService->delOrderDzData($data, 'order_qyzs');
            $systemOperateLogModel->addOperate($uid, message::$ORDER, '企业证书-编辑');

        } catch (\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_OPERATE);
    }

    //企业证书第二步
    public function editEnterPriseCers(
        Request                            $request,
        OrderEnterpriseCertificateBusiness $business,
        Certificate                        $certificateSer,
        OrderLog                           $orderLogModel,
        Image                              $image,
        SystemOperateLog                   $systemOperateLogModel,
        RedisService                       $redisService
    )
    {
        $param = $certificateSer->splitCer($request->post());
        $uid = $request->post('user_login_id');
        $information_file = $request->file('information_file');
        $contract_file = $request->file('contract_file');
        if (empty($param['id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

//        //判断是否有文件上传
//        if(!empty($information_file)){
//            $param['information_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $information_file);
//        }
//
//        if (!empty($contract_file)){
//            $param['contract_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $contract_file);
//        }
//
//        //去掉url http
//        $str = "file/";
//
//        if (!empty($param['contract_file'])){
//            $param['contract_file'] = strstr($param['contract_file'],$str);
//        }
//        if (!empty($param['information_file'])){
//            $param['information_file'] = strstr($param['information_file'],$str);
//        }
        if (isset($param['contract_file'])) {
            $array = $image->handle($param['contract_file'], 'contract_file', 'contract_file_name');
            $param['contract_file'] = $array['contract_file'];
            $param['contract_file_name'] = $array['contract_file_name'];
        }
        if (isset($param['information_file'])) {
            $array = $image->handle($param['information_file'], 'information_file', 'information_file_name');
            $param['information_file'] = $array['information_file'];
            $param['information_file_name'] = $array['information_file_name'];
        }

        //ad_performance=0 修改业绩
        $data = $business->getWhereIdDataModel($param['id']);
        if ($data['ad_performance'] == 0) {
            //计算该订单业绩
            if ($param['sale_price'] > 1 && $param['cost_price'] > 1) {
                //修改订单状态为办理中
                $param['performance'] = $param['sale_price'] - $param['cost_price'] ?: 0;
            }
        }

        try {
            //编辑补充资料
            $business->editDataModel($param);

            //查询证书编号
            $certificate = $business->getWhereIdDataModel($param['id']);

            if ($certificate['status']['id'] == 4) {

                //修改为待审核
                $business->saveStatusInitModel($param);

                //添加订单日志
                $orderLogModel->addDataModel([
                    'order_company_id' => $param['id'],
                    'message' => message::$ORDER_ENPER_PRISE_BUSINESS_CXLD,
                    'certificate_code' => $certificate['certificate_code'],
                    'submit_id' => $uid
                ]);
            }
            //删除业绩总表缓存
            $redisService->delPerformance($certificate);
            //删除订单缓存
            $redisService->delOrderDzData($certificate, 'order_qyzs');
            $systemOperateLogModel->addOperate($uid, message::$ORDER, '企业证书-补充');
        } catch (\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_OPERATE);
    }

    //删除企业证书
    public function delEnterPriseCer(
        Request                            $request,
        OrderEnterpriseCertificateBusiness $business,
        SystemOperateLog                   $systemOperateLogModel,
        RedisService                       $redisService
    )
    {
        $id = $ids = $request->post('id');
        $uid = $request->post('user_login_id');
        $id = explode(',', $id);

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
//        //查询是否成交
//        $data = $business->getWhereIdDataModel($id);
//
//        if ($data['status'] == 1) {
//            return ReJson(message::$ERROR_CODE, message::$ORDER_ENPER_PRISE_BUSINESS_STATUS_ERR);
//        }
        $data = $business->getWhereIdDataModel($id);

        $business->delIdData($id);
        //删除业绩总表缓存
        $redisService->delPerformance($data);
        //删除订单缓存
        $redisService->delOrderDzData($data, 'order_qyzs');
        //更新财务报表业绩统计缓存
        $redisService->updateDateBetweenData($data['sale_date'],$data['sale_date']);

        $systemOperateLogModel->addOperate($uid, message::$ORDER, '企业证书-删除:' . $ids);

        return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }


    //确认企业证书
    public function createEnterPriseCer(
        Request                            $request,
        OrderLog                           $log,
        OrderEnterpriseCertificateBusiness $business,
        OrderDeal                          $deal,
        User                               $user,
        Gateway                            $gateway,
        \app\service\User                  $userService,
        SystemOperateLog                   $systemOperateLogModel,
        RedisService                       $redisService,
        \app\model\ClueEnterprise $enterpriseModel
    )
    {
        $id = $request->post('id');
        $uid = $request->post('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $find = $business->getWhereIdDataModel($id);

        if (empty($find)) {
            return ReJson(message::$ERROR_CODE, message::$SELECT_CERTIFICATE_ERR);
        }

        //查询status 是否为代出售状态
//        if ($find['status']['id'] != 0) {
//            return ReJson(message::$ERROR_CODE, message::$ORDER_ENPER_PRISE_BUSINESS_STATUS);
//        }

        Db::startTrans();
        try {
            //修改证书状态为生产中
            $business->editDataModel([
                'id' => $id,
                'status' => $this->ORDER_SCZ_STATUS,
                'sale_date' => date('Y-m-d H:i:s')
            ]);

            //添加订单日志
            $log->addDataModel([
                'order_company_id' => $id,
                'message' => message::$ORDER_ENPER_PRISE_BUSINESS_PRODUCTION,
                'submit_id' => $request->param('user_login_id'),
//                'type'=>$this->ORDER_LOG_ENTERPRISE_BUSINESS,
                'certificate_code' => $find['certificate_code']
            ]);

            //添加成交记录
//            $deal->addOrderDataModel([
////                'order_company_id' =>$id,
//                'certificate_code' => $find['certificate_code'],
//                'status' => $this->ORDER_DEAL_STATUS,
////                'type'=>$this->ORDER_DEAL_TYPE_ENTERPRISE_BUSINESS,
//            ]);

//            //发送全局成交
            $gateway->sendToAll(json_encode([
                'type'=>'deal',
                'content'=>$userService->getUidOrgTitle ($uid),
                'nickname'=>$user->getIdNickName($uid),
                'title'=>date('Y-m-d H:i:s')."成交了企业证书！"
            ]));
            $data = $business->getWhereIdDataModel($id);
            //删除业绩总表缓存
            $redisService->delPerformance($data);
            //删除订单缓存
            $redisService->delOrderDzData($data, 'order_qyzs');
            //删除企业库ID缓存
            $redisService->delEnterData ($enterpriseModel->getEnterNameGetIdModel ($data['enterprise_name'],$uid)['id']);

            $systemOperateLogModel->addOperate($uid, message::$ORDER, '企业证书-确认');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$ORDER_ENPER_PRISE_BUSINESS_PRODUCTION);
    }

    //完成
    public function enterBusinessComplete(
        Request                            $request,
        OrderLog                           $log,
        OrderEnterpriseCertificateBusiness $business,
        OrderDeal                          $deal,
        User                               $user,
        Gateway                            $gateway,
        \app\service\User                  $userService,
        SystemOperateLog                   $systemOperateLogModel,
        RedisService                       $redisService,
        \app\model\ClueEnterprise $enterpriseModel
    )
    {
        $id = $request->post('id');
        $uid = $request->post('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $find = $business->getWhereIdDataModel($id);

        if (empty($find)) {
            return ReJson(message::$ERROR_CODE, message::$SELECT_CERTIFICATE_ERR);
        }

        //查询status 是否为代出售状态
//        if ($find['status']['id'] != 0) {
//            return ReJson(message::$ERROR_CODE, message::$ORDER_ENPER_PRISE_BUSINESS_STATUS);
//        }

        Db::startTrans();
        try {
            //修改证书状态为完结
            $business->editDataModel([
                'id' => $id,
                'status' => $this->ORDER_DEAL_STATUS
            ]);

            //添加订单日志
            $log->addDataModel([
                'order_company_id' => $id,
                'message' => message::$ORDER_ENPER_PRISE_BUSINESS,
                'submit_id' => $request->param('user_login_id'),
//                'type'=>$this->ORDER_LOG_ENTERPRISE_BUSINESS,
                'certificate_code' => $find['certificate_code']
            ]);

            //添加成交记录
            $deal->addOrderDataModel([
                'order_company_id' => $id,
                'certificate_code' => $find['certificate_code'],
                'status' => $this->ORDER_DEAL_STATUS,
//                'type'=>$this->ORDER_DEAL_TYPE_ENTERPRISE_BUSINESS,
            ]);

            //发送全局成交
            $gateway->sendToAll(json_encode([
                'type' => 'deal',
                'content' => $userService->getUidOrgTitle($find['submit_id']),
                'nickname' => $user->getIdNickName($find['submit_id']),
                'title' => date('Y-m-d H:i:s') . "成交了企业证书！"
            ]));

            $data = $business->getWhereIdDataModel($id);
            //删除业绩总表缓存
            $redisService->delPerformance($data);
            //删除订单缓存
            $redisService->delOrderDzData($data, 'order_qyzs');
            //删除企业库ID缓存
            $redisService->delEnterData ($enterpriseModel->getEnterNameGetIdModel ($data['enterprise_name'],$uid)['id']);

            $systemOperateLogModel->addOperate($uid, message::$ORDER, '企业证书-完成');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$ORDER_ENPER_PRISE_BUSINESS);
    }

    //企业证书驳回
    public function enterBusinessReject(
        Request                            $request,
        OrderLog                           $log,
        OrderEnterpriseCertificateBusiness $business,
        OrderDeal                          $deal,
        User                               $user,
        Gateway                            $gateway,
        \app\service\User                  $userService,
        SystemOperateLog                   $systemOperateLogModel,
        RedisService                       $redisService
    )
    {
        $id = $request->post('id');
        $uid = $request->post('user_login_id');
        $reject_text = $request->post('reject_text');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $find = $business->getWhereIdDataModel($id);

        if (empty($find)) {
            return ReJson(message::$ERROR_CODE, message::$SELECT_CERTIFICATE_ERR);
        }

        //查询status 是否为代出售状态
//        if ($find['status']['id'] != 0) {
//            return ReJson(message::$ERROR_CODE, message::$ORDER_ENPER_PRISE_BUSINESS_STATUS);
//        }

        Db::startTrans();
        try {
            //修改证书状态为已驳回
            $business->editDataModel([
                'id' => $id,
                'status' => 4, //驳回状态
                'reject_text' => $reject_text
            ]);

            //添加订单日志
            $log->addDataModel([
                'order_company_id' => $id,
                'message' => message::$ORDER_ENPER_PRISE_BUSINESS_YBH,
                'submit_id' => $request->param('user_login_id'),
//                'type'=>$this->ORDER_LOG_ENTERPRISE_BUSINESS,
                'certificate_code' => $find['certificate_code']
            ]);

            $data = $business->getWhereIdDataModel($id);
            //删除业绩总表缓存
            $redisService->delPerformance($data);
            //删除订单缓存
            $redisService->delOrderDzData($data, 'order_qyzs');

            $systemOperateLogModel->addOperate($uid, message::$ORDER, '企业证书-驳回');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$ORDER_ENPER_PRISE_BUSINESS_YBH);
    }
    /*****************************************************************证书办理*****************************************************************************/

    //证书办理列表
    public function getCerHandle(
        Request                       $request,
        Power                         $power,
        OrderOtherCertificateBusiness $handle,
        Clue                          $clue,
        \app\service\Order            $orderSer,
        OrderCertTransact             $orderCertTransact,
        Image                         $image,
        FinanceServer                 $financeServer,
        OrderDealChargeback           $chargebackModel
    )
    {
        $aliasId = $request->get('aliasId');

        $page = $request->get('page') ?: 0;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $uid = $request->param('user_login_id');
        //根据条件查询用户范围
        $userData = $power->getUserDataRange($uid);

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        $param = $request->get();
        $validate = new \app\validate\OrderCertTransact();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }
        $flag = flagStatus($param);
        $ids = $orderCertTransact->spliceWhere($param);
        $ids = !$ids ? [0] : $ids;

        $all_ids = $handle->getDataIds($userData);

        $ids = handlePersonIds($all_ids, $ids, $flag);

        $datas = $handle->getDataModel($page, $pageNum, $ids);

        //查询退单
        $chargebackData = $chargebackModel->getCharDataModel();
        if (!empty($chargebackData)) {
            foreach ($chargebackData as $chargebackDatum) {
                $tData = $handle->getCerDataModel($chargebackDatum['certificate_code']);

                if ($tData) {
//                    //判断个人还是管理 增加响应退单内容
                    $idArr = array_column($datas, 'id');
                    if (in_array($tData['id'], $idArr)) {

//                        if ($chargebackDatum['performance'] > 0){
//                            $tData['performance'] = '-'.$chargebackDatum['performance'];
//                        }else{
                        $tData['performance'] = $chargebackDatum['performance'];
//                        }

                        $tData['create_date'] = $chargebackDatum['create_date'];
                        $tData['sale_date'] = $chargebackDatum['create_date'];

                        $tData['tuidan'] = true;
                        $tData['reason'] = $chargebackDatum['reason'];
                        $tData['status'] = [
                            'id' => 999,
                            'text' => '退单完成'
                        ];
                        $datas[] = $tData;
                    }
                }
            }
        }
        $result = $orderSer->getMianOrderInfo($datas);
        $where['start_performance'] = $param['start_performance'] ?? '';
        $where['end_performance'] = $param['end_performance'] ?? '';
        $where['c_status'] = $param['status'];
        $where['start_sale_date'] = $param['sale_start_date'];
        $where['end_sale_date'] = $param['sale_end_date'];
        //条件筛选
        $result = $financeServer->resultSearchHandle($where, $result);

        $pages['total'] = count($result);
        $pages['pageNumber'] = $pageNum;
        $result = $image->handleList($result, ['contract_file', 'information_file'], true);
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            //查询是否有定时器
            'data' => page($orderSer->whDingshiqi($result), $page, $pageNum, 'desc', 'sale_date'),
            'power' => $fieldListTree
        ], $pages);
    }

    //个人证书办理列表
    public function getThatPersonCerHandleList(
        Request                       $request,
        Power                         $power,
        OrderOtherCertificateBusiness $handle,
        \app\service\Order            $orderSer,
        OrderCertTransact             $orderCertTransact,
        FinanceServer                 $financeServer,
        OrderDealChargeback           $chargebackModel
    )
    {
        $aliasId = $request->get('aliasId');
        $uid = $request->get('user_login_id');
        $page = $request->get('page') ?: 0;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $fieldListTree = $power->getUserFieldPower($aliasId, $request->get('user_login_id'));

        $param = $request->get();
        $validate = new \app\validate\OrderCertTransact();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }

        $flag = flagStatus($param);

        $ids = $orderCertTransact->spliceWhere($param);

        $ids = !$ids ? [0] : $ids;
        $all_ids = $handle->getThatPersonDataIds($request->param('user_login_id'));
        $ids = handlePersonIds($all_ids, $ids, $flag);
        //getOrderIsOp 查询是否有退单或者注销操作
        $datas = $handle->getThatPersonDataModel($uid, $ids, $page);
        //查询退单
        $chargebackData = $chargebackModel->getCharDataModel();
        if (!empty($chargebackData)) {
            foreach ($chargebackData as $chargebackDatum) {
                $tData = $handle->getCerDataModel($chargebackDatum['certificate_code']);

                if ($tData) {
                    //判断个人还是管理 增加响应退单内容
                    $idArr = array_column($datas, 'id');
                    if (in_array($tData['id'], $idArr)) {

                        $tData['performance'] = $chargebackDatum['performance'];

                        $tData['create_date'] = $chargebackDatum['create_date'];
                        $tData['sale_date'] = $chargebackDatum['create_date'];

                        $tData['tuidan'] = true;
                        $tData['reason'] = $chargebackDatum['reason'];
                        $tData['status'] = [
                            'id' => 999,
                            'text' => '退单完成'
                        ];
                        $datas[] = $tData;
                    }
                }
            }
        }


        $result = $orderSer->getMianOrderInfo($datas);
        $where['start_performance'] = $param['start_performance'] ?? '';
        $where['end_performance'] = $param['end_performance'] ?? '';
        $where['c_status'] = $param['status'];
        $where['start_sale_date'] = $param['sale_start_date'];
        $where['end_sale_date'] = $param['sale_end_date'];
        //条件筛选
        $result = $financeServer->resultSearchHandle($where, $result);

        $pages['total'] = count($result);
        $pages['pageNumber'] = $pageNum;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => page($orderSer->whDingshiqi($result), $page, $pageNum, 'desc', 'sale_date'),
            'power' => $fieldListTree
        ], $pages);
    }

    //证书办理详情
    public function getEnterPriseCerHandleDetails(
        Request                        $request,
        OrderOtherCertificateBusiness  $business,
        OrderLog                       $log,
        \app\service\Order             $orderSer,
        OrderPersonCertificateRegister $OrderPersonCertificateRegisterModel,
        OrderEnterpriseCompany         $OrderEnterpriseCompanyModel,
        Power                          $power,
        Image                          $image
    )
    {
        $id = $request->get('id');
        $uid = $request->get('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //企业证书内容
        $result['data'] = $business->getWhereIdDataModel($id);

        if (empty($result)) {
            return ReJson(message::$ERROR_CODE, message::$SELECT_CERTIFICATE_ERR);
        }
        //获取订单日志
        $order_log = $log->getCertificateCodeFindDataModel($result['data']['certificate_code']);

        //收款信息
        $result['collection'] = $orderSer->getCerTransaction($result['data']['certificate_code'], $this->Collection);

        //付款信息
        $result['payment'] = $orderSer->getCerTransaction($result['data']['certificate_code'], $this->Payment);

        //所有主订单信息
        $personData = $OrderPersonCertificateRegisterModel->getDataModel();
        $zszcField = $power->getUserFieldPower('ddzszccj', $uid);//证书注册
        $zsshField = $power->getUserFieldPower('ddzssh', $uid);//证书审核
        $mainOrderData = [];

        foreach ($personData as $orderDatum) {

            $arr = explode(',', $orderDatum['ancillary_businesses_id']);
            if (empty($arr)) {
                continue;
            }
            if (in_array($id, $arr, true)) {

                //如果已经售卖 通过身份证号码查询售卖信息
                if ($orderDatum['status']['id'] == 3) {
                    $companyData = $OrderEnterpriseCompanyModel->getPersonIdCardFindModel($orderDatum['person_id_card']);
                    if ($companyData) {
                        foreach ($companyData[0] as $k => $companyDatum) {
                            //如果是获取器数组 则只去text
                            if (is_array($companyDatum)) {
                                if (isset($companyDatum['text'])) {
                                    $companyDatum = $companyDatum['text'] ?: '';
                                }
                            }

                            $mainOrderData[0]['id'] = $companyData[0]['id'];
                            $mainOrderData[0]['bh'] = $companyData[0]['certificate_code'];
                            $mainOrderData[0]['create_date'] = $companyData[0]['create_date'];
                            $mainOrderData[0]['leixing'] = '证书注册';
//                print_r ($k);
//                echo PHP_EOL;
                            if ($k == 'status') {
                                $mainOrderData[0]['status'] = $companyDatum;
                            }
                            foreach ($zszcField as $zszciItem) {
                                //如果模板字段等于订单详情字段 拼接字段name
                                if ($k == $zszciItem['alias_field_id']) {
                                    if (!empty($zszciItem['name'])) {
                                        $mainOrderData[0]['info'][] = ['id' => $zszciItem['name'], 'text' => $companyDatum];
                                    }
                                }
                            }
                        }
                        unset($companyData);
                        break;
                    }
                } else {
                    $companyData = $OrderPersonCertificateRegisterModel->getIdDetails($orderDatum['id']);
                    if ($companyData) {
                        foreach ($companyData as $key => $arrDatum) {
                            //如果是获取器数组 则只去text
                            if (is_array($arrDatum)) {
                                if (isset($arrDatum['text'])) {
                                    $arrDatum = $arrDatum['text'] ?: '';
                                }
                            }

                            $mainOrderData[0]['id'] = $companyData['id'];
                            $mainOrderData[0]['bh'] = $companyData['certificate_code'];
                            $mainOrderData[0]['create_date'] = $companyData['create_date'];
                            $mainOrderData[0]['leixing'] = '证书审核';
                            if ($key == 'status') {
                                $mainOrderData[0]['status'] = $arrDatum;
                            }
                            foreach ($zsshField as $zsshiItem) {
                                //如果模板字段等于订单详情字段 拼接字段name
                                if ($key == $zsshiItem['alias_field_id']) {
                                    if (!empty($zsshiItem['name'])) {
                                        $mainOrderData[0]['info'][] = ['id' => $zsshiItem['name'], 'text' => $arrDatum];
                                    }
                                }
                            }
                        }
                    }
                    unset($companyData);
                    break;
                }
            }
        }
        $result['order_log'] = $mainOrderData;
        $result['data'] = $image->handleList($result['data'], ['contract_file', 'information_file']);
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => $result,
            'log' => $order_log
        ]);
    }

    //通过附属业务证书办理查询主订单
    public function getMainOrderDetails(
        Request                        $request,
        OrderPersonCertificateRegister $OrderPersonCertificateRegisterModel
    )
    {
        $id = $request->get('id');
        $orderData = $OrderPersonCertificateRegisterModel->getDataModel();
        if ($orderData) {
            foreach ($orderData as $orderDatum) {
                $arr = explode(',', $orderDatum['ancillary_businesses_id']);
                if (in_array($id, $arr, true)) {
                    return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $orderDatum);
                }
            }
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA);
    }


    //修改证书办理
    public function editEnterPriseHandle(
        Request                       $request,
        OrderOtherCertificateBusiness $business,
        Certificate                   $certificateSer,
        Image                         $image,
        SystemOperateLog              $systemOperateLogModel,
        RedisService                  $redisService,
        OrderEnterpriseCompany $enterpriseCompanyModel
    )
    {
        $param = $certificateSer->splitCer($request->post());
        $uid = $request->post('user_login_id');

        $information_file = $request->file('information_file');
        $contract_file = $request->file('contract_file');
        if (empty($param['id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //先查看业绩是否被财务修改过
        //ad_performance=0 修改业绩
        $data = $business->getWhereIdDataModel($param['id']);
        if ($data['ad_performance'] == 0) {
            $param['performance'] = $param['sale_price'] - $param['cost_price'];
        }
//        //判断是否有文件上传
//        if(!empty($information_file)){
//            $param['information_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $information_file);
//        }
//
//        if (!empty($contract_file)){
//            $param['contract_file'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $contract_file);
//        }
        $array = $image->handle($param['contract_file'], 'contract_file', 'contract_file_name');
        $param['contract_file'] = $array['contract_file'];
        $param['contract_file_name'] = $array['contract_file_name'];
        $array = $image->handle($param['information_file'], 'information_file', 'information_file_name');
        $param['information_file'] = $array['information_file'];
        $param['information_file_name'] = $array['information_file_name'];

        try {
            $business->editDataModel($param);
            //操作附属单的同时更新证书注册业绩总表的缓存
            if ($data['type'] == 1){
                //通过证书办理人才身份证查询对应证书注册信息
                $datas = $enterpriseCompanyModel->getIdCardOrderInfoModel ($data['person_id_card']);
                //删除业绩总表缓存
                $redisService->delPerformance($datas);
            }
            //删除业绩总表缓存
            $redisService->delPerformance($data);
            //删除订单缓存
            $redisService->delOrderDzData($data, 'order_zsbl');
            $systemOperateLogModel->addOperate($uid, message::$ORDER, '证书办理-修改');
        } catch (\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    //删除证书办理
    public function delCerHandle(
        Request                       $request,
        OrderOtherCertificateBusiness $business,
        SystemOperateLog              $systemOperateLogModel,
        RedisService                  $redisService
    )
    {
        $id = $ids = $request->post('id');
        $uid = $request->post('user_login_id');
        $id = explode(',', $id);

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        //查询是否成交
//        $data = $business->getWhereIdDataModel($id);
//        if ($data['status'] == 1) {
//            return ReJson(message::$ERROR_CODE, message::$ORDER_ENPER_PRISE_BUSINESS_STATUS_ERR);
//        }
        $data = $business->getWhereIdDataModel($id);
        $business->delDataModel($id);
        //删除业绩总表缓存
        $redisService->delPerformance($data);
        //删除订单缓存
        $redisService->delOrderDzData($data, 'order_zsbl');
        //更新财务报表业绩统计缓存
        $redisService->updateDateBetweenData($data['sale_date'],$data['sale_date']);
        $systemOperateLogModel->addOperate($uid, message::$ORDER, '证书办理-删除' . $ids);

        return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }

    //确认证书办理
    public function createCerHandle(
        Request                       $request,
        OrderLog                      $log,
        OrderOtherCertificateBusiness $business,
        OrderDeal                     $deal,
        Gateway                       $gateway,
        User                          $user,
        \app\service\User             $userService,
        SystemOperateLog              $systemOperateLogModel,
        RedisService                  $redisService,
        OrderEnterpriseCompany $enterpriseCompanyModel,
        CluePerson $personModel
    ){
        $id = $request->post('id');
        $uid = $request->post('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $find = $business->getWhereIdDataModel($id);

        //查询status 是否为代确认状态
        if ($find['status']['id'] != 11) {
            return ReJson(message::$ERROR_CODE, message::$ORDER_ENPER_PRISE_BUSINESS_NO_STATUS_QR);
        }

        Db::startTrans();
        try {
            //修改证书状态为确认
            $business->editDataModel([
                'id' => $id,
                'status' => 12,
                'sale_date' => date('Y-m-d H:i:s')
            ]);

            //添加订单日志
            $log->addDataModel([
                'submit_id' => $request->param('user_login_id'),
                'order_company_id' => $id,
                'message' => message::$ORDER_ENPER_PRISE_BUSINESS_PRODUCTION,
//                'type'=>$this->ORDER_LOG_ENTERPRISE_CER,
                'certificate_code' => $find['certificate_code']
            ]);

            //添加成交记录
//            $deal->addOrderDataModel([
//                'certificate_code' => $find['certificate_code'],
//                'status' => $this->ORDER_DEAL_STATUS,
////                'type'=>$this->ORDER_DEAL_TYPE_CER,
//            ]);
            //发送全局成交
//            $gateway->sendToAll(json_encode([
//                'type'=>'deal',
//                'content'=>$userService->getUidOrgTitle ($uid),
//                'nickname'=>$user->getIdNickName($uid),
//                'title'=> date('Y-m-d H:i:s')."成交了证书办理！"
//            ]));
            $data = $business->getWhereIdDataModel($id);
            //操作附属单的同时更新证书注册业绩总表的缓存
            if ($data['type'] == 1){
                //通过证书办理人才身份证查询对应证书注册信息
                $datas = $enterpriseCompanyModel->getIdCardOrderInfoModel ($data['person_id_card']);
                //删除业绩总表缓存
                $redisService->delPerformance($datas);
            }

            //删除业绩总表缓存
            $redisService->delPerformance($data);
            //删除订单缓存
            $redisService->delOrderDzData($data, 'order_zsbl');
            //删除人才库ID缓存
            $redisService->delPersonData ($personModel->getPersonIdCardInfo ($data['person_id_card'])['id']);
            $systemOperateLogModel->addOperate($uid, message::$ORDER, '证书办理-确认');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$ORDER_ENPER_PRISE_BUSINESS_PRODUCTION);
    }

    //完成证书办理
    public function completeHandle(
        Request                       $request,
        OrderLog                      $log,
        OrderOtherCertificateBusiness $business,
        OrderDeal                     $deal,
        Gateway                       $gateway,
        User                          $user,
        \app\service\User             $userService,
        SystemOperateLog              $systemOperateLogModel,
        RedisService                  $redisService,
        OrderEnterpriseCompany $enterpriseCompanyModel,
        CluePerson $personModel
    )
    {
        $id = $request->post('id');
        $uid = $request->post('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $find = $business->getWhereIdDataModel($id);

        //查询status 是否为代出售状态
        if ($find['status']['id'] != 12) {
            return ReJson(message::$ERROR_CODE, message::$ORDER_ENPER_PRISE_BUSINESS_NO_STATUS_SC);
        }

        Db::startTrans();
        try {
            //修改证书状态为完结
            $business->editDataModel([
                'id' => $id,
                'status' => $this->ORDER_DEAL_STATUS
            ]);

            //添加订单日志
            $log->addDataModel([
                'submit_id' => $request->param('user_login_id'),
                'message' => message::$ORDER_ENPER_PRISE_BUSINESS,
//                'type'=>$this->ORDER_LOG_ENTERPRISE_CER,
                'order_company_id' => $id,
                'certificate_code' => $find['certificate_code']
            ]);

            //添加成交记录
            $deal->addOrderDataModel([
                'order_company_id' => $id,
                'certificate_code' => $find['certificate_code'],
                'status' => $this->ORDER_DEAL_STATUS,
//                'type'=>$this->ORDER_DEAL_TYPE_CER,
            ]);
            //发送全局成交
            $gateway->sendToAll(json_encode([
                'type' => 'deal',
                'content' => $userService->getUidOrgTitle($find['get_uid']['id']),
                'nickname' => $user->getIdNickName($find['get_uid']['id']),
                'title' => date('Y-m-d H:i:s') . "成交了证书办理！"
            ]));

            $data = $business->getWhereIdDataModel($id);
            //操作附属单的同时更新证书注册业绩总表的缓存
            if ($data['type'] == 1){
                //通过证书办理人才身份证查询对应证书注册信息
                $datas = $enterpriseCompanyModel->getIdCardOrderInfoModel ($data['person_id_card']);
                //删除业绩总表缓存
                $redisService->delPerformance($datas);
            }
            //删除业绩总表缓存
            $redisService->delPerformance($data);
            //删除订单缓存
            $redisService->delOrderDzData($data, 'order_zsbl');
            //删除人才库ID缓存
            $redisService->delPersonData ($personModel->getPersonIdCardInfo ($data['person_id_card'])['id']);
            $systemOperateLogModel->addOperate($uid, message::$ORDER, '证书办理-完成');

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$ORDER_ENPER_PRISE_BUSINESS);
    }

    //补充公示资料
    public function supplementInfo(Request $request, OrderEnterpriseCertificateRegister $enterpriseCertificateRegister, OrderDeal $deal)
    {
        $param = $request->post();

        $electronic_certificate_file = $request->file('electronic_certificate_file');

        $b_electronic_certificate_file = $request->file('b_electronic_certificate_file');

        if (empty($param['id']) || empty($param['certificate_code'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //查询该订单是否已经成交
        if (empty($deal->getOrderCompanyIdFindModel($param['id'], $param['certificate_code']))) {
            return ReJson(message::$ERROR_CODE, message::$ORDER_NOHAVE_DEAL);
        }

        if (!empty($b_electronic_certificate_file)) {
            $param['b_electronic_certificate_file_name'] = $b_electronic_certificate_file->getOriginalName();
            $param['b_electronic_certificate_file'] = \think\facade\Filesystem::disk('public')->putFile('file', $b_electronic_certificate_file);
        }
        if (!empty($electronic_certificate_file)) {
            $param['electronic_certificate_file_illustrate_name'] = $electronic_certificate_file->getOriginalName();
            $param['electronic_certificate_file'] = \think\facade\Filesystem::disk('public')->putFile('file', $electronic_certificate_file);
        }
        $deal->editDataModel($param);

        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    //获取证书补充资料
    public function getSupplementInfo(Request $request, OrderEnterpriseCertificateRegister $enterpriseCertificateRegister, OrderDeal $deal)
    {
        $id = $request->get('id');
        $certificate_code = $request->get('certificate_code');

        if (empty($id) || empty($certificate_code)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $result = $deal->getsuppleInfo($id, $certificate_code);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    /**
     * 证书办理收付款详情
     * @param Request $request
     * @param OrderTransactionRecord $orderTransactionRecord
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function receiptPaymentDetails(
        Request                 $request,
        OrderTransactionRecord  $orderTransactionRecord,
        Image                   $image,
        OrderEnterpriseCompany  $enterpriseCompanyModel,
        OrderEnterpriseExchange $orderEnterpriseExchangeModel
    )
    {
        $id = $request->get('id');
        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        $result = $orderTransactionRecord->getInfo($id);
        if (!$result) {
            return ReJson(message::$ERROR_CODE, '收付款信息不存在');
        }
        $result = $result->toArray();
        $result = $image->handleList($result, ['annex']);
        //根据code去找应付款和已付款
        $data = [];
        //证书办理
        $otherBusiness = Db::table('order_other_certificate_business')
            ->where('certificate_code', $result['certificate_code'])
            ->find();
        //公司证书
        $company = $enterpriseCompanyModel->getIdCertificateCodeFindModel($result['order_company_id'], $result['certificate_code']);
        //倒证
        $exchange = $orderEnterpriseExchangeModel->getFinanceFieldFindModel($result['certificate_code']);

        if ($otherBusiness) {
            $data['sale_price'] = $otherBusiness['sale_price'];
            $data['cost_price'] = $otherBusiness['cost_price'];
            $data['person_name'] = $otherBusiness['person_name'];
        } else if ($company) {
            $data['sale_price'] = $company['price_unit'];
            $data['cost_price'] = $company['contract_price'];
            $data['person_name'] = $company['person_name'];
        } else if ($exchange) {
            $data['sale_price'] = $exchange['out_price'];
            $data['cost_price'] = $exchange['get_price'];
            $data['person_name'] = $exchange['person_name'];
        }


        $data['certificate_code'] = $result['certificate_code'];
        //已付款
        $data['money_receipt'] = Db::table('order_transaction_record')
            ->where(['certificate_code' => $result['certificate_code'], 'order_company_id' => $result['order_company_id']])
            ->where('status', 1)
            ->where('id', '<', $result['id'])
            ->where('transaction_type', 2)
            ->sum('price');

        //已收款
        $data['money_collection'] = Db::table('order_transaction_record')
            ->where(['certificate_code' => $result['certificate_code'], 'order_company_id' => $result['order_company_id']])
            ->where('status', 1)
            ->where('id', '<', $result['id'])
            ->where('transaction_type', 1)
            ->sum('price');

//        if ($result['status']['id'] == 1){
//            $data['money_collection'] = $data['money_collection'] - $result['price'];
//            if ($data['money_collection'] < 0) $data['money_collection'] = 0;
//            $data['money_receipt'] = $data['money_receipt'] - $result['price'];
//            if ($data['money_receipt'] < 0) $data['money_receipt'] = 0;
//        }
        $data['price'] = $result['price'];
        $data['notes'] = $result['notes'];
        $result['arr'][] = $data;
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    /**
     * 企业证书详情
     * @param Request $request
     * @param OrderTransactionRecord $orderTransactionRecord
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function enterCertPaymentDetails(
        Request                $request,
        OrderTransactionRecord $orderTransactionRecord,
        Image                  $image
    )
    {
        $id = $request->get('id');
        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        $result = $orderTransactionRecord->getInfo($id);
        if (!$result) {
            return ReJson(message::$ERROR_CODE, '收付款信息不存在');
        }
        $result = $result->toArray();
        $result = $image->handleList($result, ['annex']);
        //根据code去找应付款和已付款
        $sale_info = Db::table('order_enterprise_certificate_business')
            ->where('certificate_code', $result['certificate_code'])
            ->find();
        $data = [];
        $data['certificate_code'] = $sale_info ? $sale_info['certificate_code'] : '';
        $data['sale_price'] = $sale_info ? $sale_info['sale_price'] : 0;
        $data['cost_price'] = $sale_info ? $sale_info['cost_price'] : 0;
        $data['person_name'] = '';
        //已付款
        $data['money_receipt'] = Db::table('order_transaction_record')
            ->where('certificate_code', $result['certificate_code'])
            ->where('id', '<', $result['id'])
            ->where('status', 1)
            ->sum('price');
        //已收款
        $data['money_collection'] = Db::table('order_transaction_record')
            ->where(['certificate_code' => $result['certificate_code'], 'order_company_id' => $result['order_company_id']])
            ->where('status', 1)
            ->where('id', '<', $result['id'])
            ->where('transaction_type', 1)
            ->sum('price');
//        if ($result['status']['id'] == 1){
//            $data['money_collection'] = $data['money_collection'] - $result['price'];
//            if ($data['money_collection'] < 0) $data['money_collection'] = 0;
//            $data['money_receipt'] = $data['money_receipt'] - $result['price'];
//            if ($data['money_receipt'] < 0) $data['money_receipt'] = 0;
//        }
        $data['price'] = $result['price'];
        $data['notes'] = $result['notes'];
        $result['arr'][] = $data;
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

}